Next.js 15 Tutorial - 5 - Routing
Routing in Next.js: Understanding File-Based Routing
Introduction to Next.js Routing
- Next.js utilizes a file system-based routing system, where the organization of files and folders in the code determines accessible URLs.
- A new project named "routing-demo" is created using
npx create-next-app, setting up a foundation for demonstrating routing.
Key Conventions in Next.js Routing
- There are three main conventions for routing in Next.js:
- All routes must reside within the
appfolder.
- Route files should be named
page.jsorpage.tsx, depending on whether TypeScript is used.
- Each folder represents a segment of the URL path.
Creating Your First Route
- To create a homepage at localhost:3000, follow these steps:
- Create an
appfolder within the source directory.
- Inside this folder, create a file named
page.tsx.
- Default export a simple React component that returns an
<h1>tag with "Welcome Home".
- Running
npm run devstarts the development server, allowing access to the homepage displaying "Welcome Home".
Layout Handling in Next.js
- The layout.tsx file is automatically generated by Next.js when accessing the root route, even if it was deleted initially. This will be explored further later.
Adding Additional Routes
- For scenario two, additional routes for an About page and Profile page need to be created:
- Create an
aboutfolder inside the app directory and add apage.tsxfile that exports a component returning "About Me".
- Similarly, create a
profilefolder with its ownpage.tsx, exporting a component that returns "My Profile".
- After saving these files, navigating to localhost:3000/about displays the About Me page while localhost:3000/profile shows My Profile.
Understanding Folder Structure and Error Handling
- The second key concept is that routes correspond directly to their respective folder names within the app directory (e.g., about maps to /about).
- If someone attempts to access an undefined URL (like /dashboard), Next.js automatically serves a 404 Not Found response without requiring additional code.
Conclusion on File-Based Routing Benefits