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
.
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 —
getStaticProps
generatesHTML
andJSON
files, both of which can be cached by a CDN for performance
When does getStaticPaths run
getStaticPaths
will only run during build in production, it will not be called during runtime. You can validate code written inside getStaticPaths
is removed from the client-side bundle with this tool.
How does getStaticProps run with regards to getStaticPaths
getStaticProps
runs duringnext build
for anypaths
returned during buildgetStaticProps
runs in the background when usingfallback: true
getStaticProps
is called before initial render when usingfallback: blocking
Where can I use getStaticPaths
getStaticPaths
must be used withgetStaticProps
- You cannot use
getStaticPaths
withgetServerSideProps
- You can export
getStaticPaths
from a Dynamic Route that also usesgetStaticProps
- You cannot export
getStaticPaths
from non-page file (e.g. yourcomponents
folder) - You must export
getStaticPaths
as a standalone function, and not a property of the page component
Runs on every request in development
In development (next dev
), getStaticPaths
will be called on every request.
Generating paths on-demand
getStaticPaths
allows you to control which pages are generated during the build instead of on-demand with fallback
. Generating more pages during a build will cause slower builds.
You can defer generating all pages on-demand by returning an empty array for paths
. This can be especially helpful when deploying your Next.js application to multiple environments. For example, you can have faster builds by generating all pages on-demand for previews (but not production builds). This is helpful for sites with hundreds/thousands of static pages.