Fix: getStaticPaths() Function Required for Dynamic Routes in Astro

Error message:
`getStaticPaths()` function is required for dynamic routes.
Routing & Pages 2025-01-25

What Causes This Error?

This error occurs when you create a dynamic route file (with brackets like [slug].astro or [...path].astro) but don’t export a getStaticPaths() function. Astro needs this function to know what pages to generate at build time.

The Problem

---
// src/pages/blog/[slug].astro
// ❌ Missing getStaticPaths export

const { slug } = Astro.params;
---

<h1>Blog post: {slug}</h1>

The Fix

Export getStaticPaths Function

---
// src/pages/blog/[slug].astro
// ✅ Add getStaticPaths export

export function getStaticPaths() {
  return [
    { params: { slug: 'post-1' } },
    { params: { slug: 'post-2' } },
    { params: { slug: 'post-3' } },
  ];
}

const { slug } = Astro.params;
---

<h1>Blog post: {slug}</h1>

With Content Collections

---
// src/pages/blog/[slug].astro
import { getCollection } from 'astro:content';

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
  }));
}

const { post } = Astro.props;
const { Content } = await post.render();
---

<h1>{post.data.title}</h1>
<Content />

Common Scenarios

Rest Parameters

---
// src/pages/docs/[...path].astro
export function getStaticPaths() {
  return [
    { params: { path: 'getting-started' } },
    { params: { path: 'guides/routing' } },
    { params: { path: 'api/reference' } },
    { params: { path: undefined } }, // Matches /docs/
  ];
}

const { path } = Astro.params;
---

<h1>Docs: {path || 'Home'}</h1>

Multiple Parameters

---
// src/pages/[lang]/[category]/[slug].astro
export function getStaticPaths() {
  return [
    { params: { lang: 'en', category: 'tech', slug: 'astro-intro' } },
    { params: { lang: 'es', category: 'tech', slug: 'astro-intro' } },
  ];
}
---

Server-Side Rendering Alternative

If you’re using SSR with an adapter, you can skip getStaticPaths:

---
// src/pages/blog/[slug].astro
export const prerender = false; // Enable SSR for this route

const { slug } = Astro.params;
// Fetch data at request time
const post = await fetchPost(slug);
---

Quick Checklist

  • Dynamic routes require getStaticPaths() export
  • Function must return an array of objects with params
  • Each param key must match the filename bracket
  • Use props to pass additional data to the page
  • For SSR, set export const prerender = false