The getStaticPaths function in Astro is used to dynamically generate URLs for pages that use dynamic routes. Here’s how it works:
-
Purpose: The primary purpose of
getStaticPathsis to specify the paths that will be statically pre-rendered by Astro. This is crucial for dynamic routes, as it allows Astro to determine all the possible routes at build time. -
Function Export: To use
getStaticPaths, you must export a function with this name from your dynamic route. This function returns an array of objects, each containing aparamsproperty. Theparamsproperty specifies the parameters for each path. -
Return Values: The
getStaticPathsfunction must return an object with the following required properties:- paths: An array of objects, each containing a
paramsproperty. Theparamsproperty should match the parameters used in the page name. For example, if your page name is[lang]/[version]/info.astro, theparamsobject should includelangandversion.
- paths: An array of objects, each containing a
-
Fallback: The
fallbackproperty can be set totrueor'blocking'. If set totrue, Astro will generate the page on the first request, while'blocking'will block the initial request until the page is generated. -
Usage: Here’s an example of how you might use
getStaticPathsin Astro:// [lang]/[version]/info.astro export async function getStaticPaths() { return { paths: [ { params: { lang: 'en', version: 'v1' } }, { params: { lang: 'fr', version: 'v2' } }, ], fallback: true, }; } // The page component can then access these parameters using Astro.params const { lang, version } = Astro.params; -
Dynamic Routes: Dynamic routes in Astro can include named parameters and rest parameters. Named parameters are specified in the filename, such as
[lang]/[version]/info.astro, while rest parameters can match any depth of the file path, such as[...path]. -
Integration with getStaticProps: The
getStaticPathsfunction is often used in conjunction withgetStaticPropsto fetch data for the statically generated pages. ThegetStaticPropsfunction runs during the build process and returns props that are used to render the page.
By using getStaticPaths, Astro can efficiently manage dynamic routes and generate all necessary pages at build time, ensuring fast and SEO-friendly performance.