Next.jsMedium

What is getStaticPaths and when is it required?

getStaticPaths tells the Pages Router which values of a dynamic route to prerender at build time. It is required when a dynamic page such as pages/posts/[id].tsx uses getStaticProps, because Next.js must know which pages to generate.

Return value

  • paths: an array like [{ params: { id: "1" } }, { params: { id: "2" } }]. Param values must be strings (or string arrays for catch-alls).
  • fallback: what to do with paths not in the list: false, true or "blocking".

Rules

  • Only for dynamic routes that use getStaticProps. It cannot be used with getServerSideProps.
  • Runs only at build time in production (and on every request in development).
  • Must be exported from the same page file.

Practical strategy

Prerender the most popular pages and let the rest generate on demand:

  • Return the top 100 IDs with fallback: "blocking".
  • For huge sites, return paths: [] with fallback: "blocking" to build nothing up front and generate every page on first visit, then cache it (with revalidate for ISR).

App Router equivalent

generateStaticParams returns plain objects ([{ id: "1" }]) and can be used at multiple levels of a nested route. Unknown params are handled by default: with Cache Components, Next.js serves the App Shell and generates the page in the background. Without Cache Components, export const dynamicParams = false returns 404 for unknown params.

Code example

tsx
1// pages/posts/[id].tsx
2import type { GetStaticPaths, GetStaticProps } from "next";
3
4export const getStaticPaths: GetStaticPaths = async () => {
5 // Only prerender the 50 most viewed posts at build time
6 const top: { id: number }[] = await fetch("https://api.example.com/posts?top=50").then((r) =>
7 r.json()
8 );
9
10 return {
11 paths: top.map((p) => ({ params: { id: String(p.id) } })), // must be strings
12 fallback: "blocking", // other ids are rendered on first request, then cached
13 };
14};
15
16export const getStaticProps: GetStaticProps = async ({ params }) => {
17 const res = await fetch(`https://api.example.com/posts/${params!.id}`);
18 if (!res.ok) return { notFound: true };
19 return { props: { post: await res.json() }, revalidate: 600 };
20};
21
22export default function Post({ post }: { post: { title: string } }) {
23 return <h1>{post.title}</h1>;
24}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app