Statically generate dynamic routes in Next.js with `getStaticPaths` and `getStaticProps`

Xiaoru Li
InstructorXiaoru Li
Share this video with your friends

Social Share Links

Send Tweet

The companion life-cycle method getStaticPaths of getStaticProps lets us use the data we have at build-time to specify which dynamic routes (like /pages/blog/[slug]) we want to generate statically.

In this lesson, we will learn how these two functions can be used in conjunction with each other to fetch mock blog data from the file system, then generate static HTML files for each blog post route. By the end of this lesson, you will be able to fully utilize the powerful Static Site Generation (SSG) feature of Next.js to build and optimize your next project.

Xiaoru Li: [0:00] Here, we have the page component for the dynamic route blog/slug. To statically generate all blog posts based on the blogs.json file, we'll need to specify what path we should generate for. To do this, we need to export an async function getStaticPaths.

[0:23] Here, we can dynamically import the content of the JSON file with await import, then default, and then, we'll get the slugs of the blog post. Then, we'll return an object with a paths property, which is going to be an array of params similar to what you get in the use router in page components.

[0:52] Let's generate this, by mapping the slugs to the paths params.

[1:02] We also need to specify that we don't want to have a fallback, so any invalid slugs will result in a 404 error. Now, the path will be individually fed into getStaticProps. We'll then need to create the getStaticProps function, which will then pass the blog entries as props into our page component.

[1:24] Here, we'll take the params out of the static props context, then grab the slug of the params. Then, we can load the blog.json file again. Let's just copy this from above. Now, let's get the blog post that we need based on the slug, and then, return the title and text of the blog entry as props.

[1:51] Now, let's go to the page component and handle the props. Now, everything works in the browser. If we build and export the website again, we'll see in the out directory that all blog posts are statically generated to HTML files.