Skip to main content

Understanding Nextjs routing

Understanding Next.js Routing

Next.js is a popular React framework with an extensive routing system. It allows you to build single-page applications, server-rendered apps, and static websites with ease. One of the features that set Next.js apart is its file-system based router. In this tutorial, we will dive deep into understanding Next.js routing.

What is Routing?

In the world of web development, routing is a mechanism where HTTP requests are routed to the code that handles them. In simpler terms, when you visit a URL on a website, the routing system determines what you see.

The Basics of Next.js Routing

In Next.js, the routing is file-system based. This means that the pages in your application correspond directly to the file system in the pages directory.

For instance, if you create a file called about.js in the pages directory, it would be accessible at the /about URL.

// pages/about.js 

export default function About() {
return <h1>About Us</h1>
}

This file would be automatically associated with the route /about.

Dynamic Routes

Next.js also supports dynamic routes. Dynamic routes are routes that have variable parts. For example, if you are building a blog and want to create a route for each blog post, you would use a dynamic route.

To create a dynamic route, you would create a file with square brackets [] in the name. The part inside the brackets is the dynamic part of the route.

// pages/posts/[id].js

export default function Post({ post }) {
// Render post...
}

This file would match any route that looks like /posts/1, /posts/2, etc.

Nested Routes

Next.js supports nested routes as well. If you create a directory inside the pages directory, it will create a nested route.

For example, if you create a directory called blog and inside that, a file called post.js, it would be associated with the route /blog/post.

// pages/blog/post.js

export default function BlogPost() {
return <h1>Blog Post</h1>
}

Linking Between Pages

Next.js provides a Link component to navigate between pages. The Link component allows you to perform client-side navigation to a different page in the application.

import Link from 'next/link'

export default function Home() {
return (
<div>
<h1>Home Page</h1>
<Link href="/about">
<a>About</a>
</Link>
</div>
)
}

In the example above, clicking on "About" will navigate you to the "About Us" page.

Conclusion

This tutorial gave you an introduction to Next.js routing. We've covered the basics of routing, dynamic and nested routes, and how to link between pages. There is much more to learn about Next.js routing, such as prefetching, programmatic navigation, and route parameters. However, with this base knowledge, you are well on your way to mastering Next.js routing. Happy coding!