How to Use getStaticPaths in Astro for Dynamic Pages
In Astro, use
export async function getStaticPaths() to define dynamic routes for static site generation. This function returns an object with a paths array of path objects that Astro uses to build pages at build time. Each path object specifies route parameters for dynamic pages.Syntax
The getStaticPaths function is an async function exported from a page component file. It returns an object with a paths array and an optional fallback boolean.
- paths: An array of objects, each with a
paramsobject defining route parameters. - fallback: When
false, only the specified paths are generated;trueenables on-demand generation.
javascript
export async function getStaticPaths() { return { paths: [ { params: { slug: 'example' } }, { params: { slug: 'another' } } ], fallback: false }; }
Example
This example shows how to create dynamic blog post pages using getStaticPaths. It generates static pages for each post slug at build time.
astro
--- export async function getStaticPaths() { const posts = [ { slug: 'hello-world' }, { slug: 'astro-tips' } ]; return { paths: posts.map(post => ({ params: { slug: post.slug } })), fallback: false }; } const { slug } = Astro.params; const postContent = { 'hello-world': 'Welcome to the Hello World post!', 'astro-tips': 'Here are some useful Astro tips.' }; --- <html lang="en"> <head> <title>{slug}</title> </head> <body> <h1>{slug}</h1> <p>{postContent[slug]}</p> </body> </html>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>hello-world</title>
</head>
<body>
<h1>hello-world</h1>
<p>Welcome to the Hello World post!</p>
</body>
</html>
Common Pitfalls
- Not returning
pathsas an array of objects withparamskeys causes build errors. - Forgetting to match dynamic route parameter names in
paramsleads to undefined values. - Setting
fallbackincorrectly can cause missing pages or runtime errors. - Using synchronous functions instead of async can break data fetching.
javascript
/* Wrong: missing params object */ export async function getStaticPaths() { return { paths: [ { slug: 'test' } // Incorrect, should be { params: { slug: 'test' } } ], fallback: false }; } /* Correct: */ export async function getStaticPaths() { return { paths: [ { params: { slug: 'test' } } ], fallback: false }; }
Quick Reference
getStaticPaths returns an object with:
paths: Array of route parameter objects, e.g.{ params: { slug: 'value' } }fallback: Boolean to enable on-demand page generation (falseby default)
Use Astro.params inside the page to access route parameters.
Key Takeaways
Always export an async getStaticPaths function returning paths with params matching your dynamic route.
Use fallback: false to pre-build only specified paths and avoid runtime errors.
Access route parameters inside the page with Astro.params for dynamic content.
Ensure paths is an array of objects with a params key to avoid build failures.
getStaticPaths enables static generation of dynamic routes at build time in Astro.