11-30-2024
One of the standout features of Next.js is its file-based routing system. It eliminates the need for setting up a routing library or manually defining routes, making it incredibly developer-friendly. In this guide, we’ll explore how file-based routing works in Next.js and how you can use it to build robust applications.
In Next.js, the pages
directory acts as the foundation for your application’s routing. Each file in this directory corresponds to a route in your application. For example:
pages/index.js
-> /
pages/about.js
-> /about
pages/contact.js
-> /contact
This intuitive approach simplifies the routing process, especially for beginners.
To create a new route, simply add a file to the pages
directory. Let’s walk through an example:
about.js
in the pages
directory.export default function AboutPage() {
return <h1>About Us</h1>;
}
http://localhost:3000/about
.That’s it! You’ve created a new route without any additional configuration.
Dynamic routing allows you to create routes that depend on dynamic parameters, such as product IDs or usernames. To create a dynamic route, use square brackets ([]
) in the file name.
[slug].js
in the pages/blog
directory.export default function BlogPost({ params }) {
const { slug } = params;
return <h1>Blog Post: {slug}</h1>;
}
export async function getServerSideProps({ params }) {
return {
props: {
params,
},
};
}
http://localhost:3000/blog/my-first-post
, and you’ll see:Blog Post: my-first-post
Next.js supports nested routes, which are created by adding folders to the pages
directory. For example:
pages/blog/index.js
-> /blog
pages/blog/[slug].js
-> /blog/:slug
index.js
inside the pages/blog
directory:export default function BlogHomePage() {
return <h1>Welcome to the Blog</h1>;
}
http://localhost:3000/blog
to see the blog home page.Next.js provides the Link
component for client-side navigation between pages. This ensures fast transitions without a full-page reload.
export default function Navbar() {
return (
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
<Link href="/blog">Blog</Link>
</nav>
);
}
Catch-all routes handle multiple dynamic segments. These are defined using square brackets with three dots (...
).
[...all].js
in the pages/docs
directory.export default function Docs({ params }) {
const { all } = params;
return <h1>Docs: {all.join(' / ')}</h1>;
}
export async function getServerSideProps({ params }) {
return {
props: {
params,
},
};
}
http://localhost:3000/docs/nextjs/routing
, and you’ll see:Docs: nextjs / routing
File-based routing in Next.js makes it incredibly easy to build and manage routes in your application. With support for static routes, dynamic routes, nested routes, and catch-all routes, you can handle almost any routing scenario with minimal effort.
Ready to explore more? Try implementing dynamic and nested routes in your Next.js project today!