Skip to main content

Dynamic Routes

Introduction to Dynamic Routes in Next.js

Dynamic routing is a feature that allows us to create pages with dynamic names in Next.js. This is typically used when we want to create a path that includes some kind of identifier. For example, a blog post might have a route like /blog/post-1.

In this tutorial, we're going to cover how you can implement dynamic routing in your Next.js applications.

Creating a Dynamic Route

To create a dynamic route, you would need to name your file with square brackets []. For example, if you want to create a dynamic route for blog posts, you could name your file as post/[id].js inside the pages directory. Here, id is the parameter that will be dynamic.

pages
└── post
└── [id].js

In the above case, any route that matches the pattern /post/anything will be served by the [id].js file.

Accessing Route Parameters

Inside your component, you can access these dynamic route parameters using the useRouter hook from next/router.

Here is an example:

import { useRouter } from 'next/router'

function Post() {
const router = useRouter()
const { id } = router.query

return <h1>Post: {id}</h1>
}

export default Post

In the above example, router.query is an object that contains the query parameters. In our case, it contains the id parameter from the route.

Fetching Data Based on Route Parameter

In many cases, you will want to fetch some data based on the route parameter. This can be done inside the getServerSideProps or getStaticProps function.

Here is an example that fetches a blog post based on the ID:

import { useRouter } from 'next/router'

function Post({ post }) {
return <h1>{post.title}</h1>
}

export async function getServerSideProps(context) {
const { id } = context.params
const response = await fetch(`https://api.example.com/posts/${id}`)
const post = await response.json()

return { props: { post } }
}

export default Post

In the above example, the getServerSideProps function is called on every request with the context object that contains the route parameters.

Summary

In this tutorial, we learned how to create dynamic routes in Next.js and how to access the route parameters inside our components. We also learned how to fetch data based on the route parameter using the getServerSideProps function.

Remember, dynamic routes are a powerful feature that allows you to create more flexible and dynamic applications. Use them wisely!