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,trueor"blocking".
Rules
- Only for dynamic routes that use
getStaticProps. It cannot be used withgetServerSideProps. - 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: []withfallback: "blocking"to build nothing up front and generate every page on first visit, then cache it (withrevalidatefor 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
1// pages/posts/[id].tsx2import type { GetStaticPaths, GetStaticProps } from "next";34export const getStaticPaths: GetStaticPaths = async () => {5 // Only prerender the 50 most viewed posts at build time6 const top: { id: number }[] = await fetch("https://api.example.com/posts?top=50").then((r) =>7 r.json()8 );910 return {11 paths: top.map((p) => ({ params: { id: String(p.id) } })), // must be strings12 fallback: "blocking", // other ids are rendered on first request, then cached13 };14};1516export 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};2122export 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.