How to Create Dynamic Routes in Next.js

Dynamic routes are pages that allow you to use custom parameters in a URL. They are especially useful when creating pages for dynamic content.


For a blog, you can use a dynamic route to construct URLs based on blog post titles. This approach is better than creating a page component for each post.

You can create dynamic routes in Next.js by defining two functions: getStaticProps and getStaticPaths.


Creating a dynamic route in Next.js

To create a dynamic route in Next.js, add parentheses to a page. For example, [params].js, [slug].js or [id].js.

For a blog, you could use a dynamic route slug. So if a post had the snail dynamic-routes-nextjsthe resulting URL would be https://example.com/dynamic-routes-nextjs.

In the pages folder, create a new file named [slug].js and create the post component that uses the post data as a prop.

const Post = ({ postData }) => {
return <div>{/* content */}</div>;
};

There are various ways you can transfer the postal data to the post office. Which method you choose depends on how you want to render the page. To get the data during creation time use getStaticProps() and to get it on demand use getServerSideProps().

Using getStaticProps to get Post data

Blog posts don’t change that often and fetching them at creation time is enough. So change the post component to include getStaticProps() .

import { getSinglePost } from "../../utils/posts";

const Post = ({ content }) => {
return <div>{/* content */}</div>;
};

export const getStaticProps = async ({ params }) => {
const post = await getSinglePost(params.slug);
return {
props: { ...post },
};
};

The getStaticProps function generates the post data rendered on the page. It uses the slug from the paths generated by the getStaticPaths function.

Using getStaticPaths to get paths

The getStaticPaths() function returns the paths for the pages to be pre-rendered. Modify the Post component to include it:

export const getStaticPaths = async () => {
const paths = getAllPosts().map(({ slug }) => ({ params: { slug } }));
return {
paths,
fallback: false,
};
};

This implementation of getStaticPaths gets all the posts to render and returns the slugs as parameters.

All in all, [slug].js looks like this:

import { getAllPosts, getSinglePost } from "../../utils/posts";

const Post = ({ content }) => {
return <div>{content}</div>;
};

export const getStaticPaths = async () => {
const paths = getAllPosts().map(({ slug }) => ({ params: { slug } }));
return {
paths,
fallback: false,
};
};

export const getStaticProps = async ({ params }) => {
const post = await getSinglePost(params.slug);

return {
props: { ...post },
};
};

export default Post;

You must use getStaticProps() and getStaticPaths() together to create a dynamic route. The getStaticPaths() function should generate the dynamic routes, while getStaticProps() retrieves the data rendered on each route.

Creating nested dynamic routes in Next.js

To create a nested route in Next.js, you need to create a new folder in the pages folder and save the dynamic route in it.

For example, to create /pages/posts/dynamic-routes-nextjs, save [slug].js inside /pages/posts.

Access to URL parameters of dynamic routes

After creating the route, you can retrieve the URL parameter from the dynamic route using the useRouter() React hook.

For the pages/[slug].js, get the slug like this:

import { useRouter } from 'next/router'

const Post = () => {
const router = useRouter()
const { slug } = router.query
return <p>Post: {slug}</p>
}

export default Post

This will display the post’s slug.

Dynamic routing with getServerSideProps

With Next.js you can get data at build time and create dynamic routes. You can use this knowledge to pre-render pages from a list of items.

If you want to get data on every request, use getServerSideProps instead of getStaticProps. Note that this approach is slower; You should only use it if you consume regularly changing data.

Leave a Reply

Your email address will not be published. Required fields are marked *