getStaticPaths
If a page has Dynamic Routes and uses getStaticProps, it needs to define a list of paths to be statically generated.
When you export a function called getStaticPaths (Static Site Generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by getStaticPaths.
export async function getStaticPaths() {
return {
paths: [
{ params: { ... } }
],
fallback: true // false or 'blocking'
};
}
getStaticPaths must be used with getStaticProps. You cannot use it with getServerSideProps.
The getStaticPaths API reference covers all parameters and props that can be used with getStaticPaths.
When should I use getStaticPaths?
You should use getStaticPaths if you’re statically pre-rendering pages that use dynamic routes and:
- The data comes from a headless CMS
- The data comes from a database
- The data comes from the filesystem
- The data can be publicly cached (not user-specific)
- The page must be pre-rendered (for SEO) and be very fast —
getStaticPropsgeneratesHTMLandJSONfiles, both of which can be cached by a CDN for performance
When does getStaticPaths run
getStaticPaths always runs on the server and never on the client. You can validate code written inside getStaticPaths is removed from the client-side bundle with this tool.
getStaticPathsruns duringnext buildfor Pages included inpathsgetStaticPathsruns on-demand in the background when usingfallback: truegetStaticPathsruns on-demand blocking rendering when usingfallback: blocking
Where can I use getStaticPaths
getStaticPaths can only be exported from a page. You cannot export it from non-page files.
Note that you must use export getStaticPaths as a standalone function — it will not work if you add getStaticPaths as a property of the page component.
Runs on every request in development
In development (next dev), getStaticPaths will be called on every request.
Related
For more information on what to do next, we recommend the following sections: