For a blog, you can use a dynamic route to create URLs based on the titles of the blog posts. 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 brackets to a page. For example, [params].js, [slug].js or [id].js.
For a blog, you could use a slug for the dynamic route. So, if a post had the slug dynamic-routes-nextjs, the resulting URL would be https://example.com/dynamic-routes-nextjs.
In the pages folder, create a new file called [slug].js and create the Post component that takes the post data as a prop.
There are different ways you can pass the post data to the Post. The method you choose depends on how you want to render the page. To fetch the data during build time, use getStaticProps() and to fetch it on request, use getServerSideProps().
Using getStaticProps to Fetch Post Data
Blog posts don’t change as often, and fetching them at build time is sufficient. So, modify the Post component to include getStaticProps().
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 Fetch Paths
The getStaticPaths() function returns the paths for the pages that should be pre-rendered. Change the Post component to include it:
This implementation of getStaticPaths fetches all the posts that should be rendered and returns the slugs as params.
Altogether, [slug].js will look like this:
You must use getStaticProps() and getStaticPaths() together to create a dynamic route. The getStaticPaths() function should generate the dynamic routes, while getStaticProps() fetches the data rendered at each route.
Creating Nested Dynamic Routes in Next.js
To create a nested route in Next.js, you need to create a new folder inside the pages folder and save the dynamic route inside it.
For example, to create /pages/posts/dynamic-routes-nextjs, save [slug].js inside /pages/posts.
Accessing URL Parameters From 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:
This will display the slug of the post.
Dynamic Routing With getServerSideProps
Using Next.js you can fetch 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 fetch data on every request, use getServerSideProps instead of getStaticProps. Note that this approach is slower; you should only use it when consuming regularly changing data.