The getStaticPaths function in Next.js is used to generate static pages for dynamic routes during the build process. It allows you to specify which dynamic routes should be pre-rendered ahead of time based on a list of paths.
In Next.js, dynamic routes are defined using square brackets in filenames (e.g., [ID].js), which creates routes like user/[ID]. The getStaticPaths function enables you to pre-generate static pages for each of these routes by returning an object containing two properties:
- paths: An array of objects specifying the dynamic parameters for each route to be pre-rendered.
- fallback: Determines how Next.js should handle paths not included in the paths array. It can be:
- false: Returns a 404 page for undefined paths.
- true: Generates the page on-demand if a requested path is not pre-rendered.
Here’s a basic example of how getStaticPaths is used:
export async function getStaticPaths() {
// Define the paths to pre-render
const paths = [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
return {
paths,
fallback: false
};
}
The above setup will pre-render static pages for user/1, user/2, and user/3 at build time.