Next.js 15 Tutorial - 6 - Nested Routes
How to Implement Nested Routes in Next.js
Overview of File-Based Routing
- The video begins by discussing Next.js's file-based routing system, explaining how
page.tsxfiles in the app folder map to root domains and subfolder routes.
- It introduces a scenario where a blog page needs to be set up at
localhost:3000/blog, along with two additional nested routes:/blog/firstand/blog/second.
Creating the Blog Page
- To create the blog page, a new folder named
blogis added inside the app directory, containing apage.tsxfile that exports a simple React component.
- The component returns an
<h1>tag with the text "My Blog", which renders correctly when navigating tolocalhost:3000/blog.
Setting Up Nested Routes
- For handling nested routes, two new folders named
firstandsecondare created within theblogfolder.
- Each of these folders contains its own
page.tsxfile. The first one exports a function calledFirstBlog, returning an<h1>tag with "First Blog Post". The second exports a function calledSecondBlog, returning "Second Blog Post".
Rendering Nested Pages
- After saving these files, navigating to
/blog/firstdisplays the first blog post as expected.
- Similarly, accessing
/blog/secondshows the second blog post. This demonstrates how easily nested routes can be implemented in Next.js.
Visualization of Route Structure
- A visualization is provided showing how each level of routing corresponds to its respective folder structure:
- Root route maps to the main app folder's
page.tsx.
- The blog route corresponds to the blog folder's
page.tsx.