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/blog
folder. - Inside the
blog
folder, create apage.js
file 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/first
and/blog/second
routes, createpage.js
files in theapp/blog/first
andapp/blog/second
folders:
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/second
shows 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.