Nested routes
In addition to basic routes, Next.js offers support for nested routes, so you can establish a hierarchical structure
within your application. Let’s aim to render a page when the user navigates to the URL localhost:3000/blog.
Furthermore,
we need to render pages for localhost:3000/blog/first and localhost:3000/blog/second.
To implement nested routes, follow these steps:
- Create a
app/blogfolder. - Inside the
blogfolder, create apage.jsfile for the main blog page:
export default function Blog() {
return <h1>My blog</h1>;
}
- Navigate to localhost:3000/blog to see the My blog page.
- To implement
/blog/firstand/blog/secondroutes, createpage.jsfiles in theapp/blog/firstandapp/blog/secondfolders:
export default function FirstBlog() {
return <h1>First blog post</h1>;
}
export default function SecondBlog() {
return <h1>Second blog post</h1>;
}
- Now, navigating to localhost:3000/blog/first displays
the first blog post, and
/blog/secondshows the second blog post.
By creating a nested folder structure, Next.js automatically routes the files accordingly. This simplifies the process of creating nested routes and enhances the organization and structure of your application.