Skip to the solution
MediumFrontend6 min read

What is generateStaticParams in Next.js and how does it enable SSG for dynamic routes?

1.1k views

The problem

Question presented to candidate: "You have app/products/[id]/page.tsx and 50,000 products. What does generateStaticParams do, what happens to an id you did not list, and how would you split the work between build time and runtime?"

What a strong answer should cover:

  • generateStaticParams returns the list of params to prerender at build time for a dynamic segment; the build shows them with the ● symbol.
  • It replaces getStaticPaths from the Pages Router.
  • By default (dynamicParams = true) other values are rendered on first request and then cached.
  • With dynamicParams = false, values not in the list return 404.
  • Returning a subset (or an empty array) trades build time for a first-visit render; fetches inside it are memoized with the page.

Clarifying questions expected:

  • "Which pages get most of the traffic?" β€” those are worth prerendering.
  • "Can valid ids appear after the build?" β€” then dynamicParams must stay true.

Code / implementation expected: Yes β€” a subset list plus the dynamicParams switch.

  • nextjs
  • generatestaticparams
  • ssg
  • dynamic-routes

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 8 sections

Read the code

Prerender the top products, render the rest on demand
// app/products/[id]/page.tsx
export const revalidate = 86400;
// export const dynamicParams = false;   // uncomment to 404 anything not listed

export async function generateStaticParams() {
  const top = await fetch("https://api.example.com/products?top=500").then((r) => r.json());
  return top.map((p: { id: number }) => ({ id: String(p.id) }));
}

export default async function Product({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await fetch(`https://api.example.com/products/${id}`).then((r) => r.json());
  return <h1>{product.name}</h1>;
}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 23 of 129 in Next.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Next.js questions
Up nextMedium

What is next/script and what are its strategy options in Next.js?

Continue