🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Routing••By Komal Nakrani

getStaticPaths in Astro, Explained with Examples

How getStaticPaths works in Astro: params and props, rest routes, content collections, API data, pagination, TypeScript types and the errors you will see.

#Astro#getStaticPaths#Routing#Dynamic Routes#Static Site

getStaticPaths() is the function a dynamic route in Astro exports to list every page it should generate at build time. A file like src/pages/blog/[slug].astro exports getStaticPaths(), returns an array of objects with params (the values for the bracketed URL segments) and optional props (data for that page), and Astro builds one HTML file per entry.

This guide explains how getStaticPaths works, shows the patterns you’ll use most, and covers typing, pagination, on-demand rendering and the common errors in Astro 7.

Key Takeaways

  • Any route with brackets in its file name, like [slug].astro or [...path].astro, needs getStaticPaths() when it is prerendered.
  • Each returned object needs params with a key for every bracket in the file name. Values must be strings (or undefined for rest params).
  • Use props to pass data you already fetched, so the page doesn’t fetch it again.
  • getStaticPaths() runs once per route, before pages render, in its own scope. Astro.props and Astro.params aren’t available inside it.
  • On-demand (server-rendered) routes don’t use getStaticPaths(); they read Astro.params at request time.

The minimal example

---
// src/pages/products/[slug].astro
export function getStaticPaths() {
  return [
    { params: { slug: 'desk-lamp' } },
    { params: { slug: 'monitor-arm' } },
    { params: { slug: 'cable-tray' } },
  ];
}

const { slug } = Astro.params;
---
<h1>Product: {slug}</h1>

Running astro build creates three pages: /products/desk-lamp/, /products/monitor-arm/ and /products/cable-tray/. Any other URL under /products/ is a 404, because only the paths you return exist. That’s what static means here: the full list is known at build time.

The function has to be exported. If a dynamic route doesn’t export it in a static build, Astro stops with the error “getStaticPaths() function required for dynamic routes.” The getStaticPaths required fix covers that case.

Params and props

params decides the URL. props carries data into the page. Combining them avoids a second lookup:

---
// src/pages/team/[member].astro
const team = [
  { id: 'ana', name: 'Ana Ruiz', role: 'Design lead' },
  { id: 'sam', name: 'Sam Okafor', role: 'Developer' },
];

export function getStaticPaths() {
  return team.map((person) => ({
    params: { member: person.id },
    props: { person },
  }));
}

const { person } = Astro.props;
---
<h1>{person.name}</h1>
<p>{person.role}</p>

That example has a subtle bug. getStaticPaths() runs in an isolated scope, before the rest of the frontmatter, so it can’t read team defined at the top level of the component. Move data into the function, or import it from another module:

// src/data/team.ts
export const team = [
  { id: 'ana', name: 'Ana Ruiz', role: 'Design lead' },
  { id: 'sam', name: 'Sam Okafor', role: 'Developer' },
];
---
// src/pages/team/[member].astro
import { team } from '../../data/team';

export function getStaticPaths() {
  return team.map((person) => ({
    params: { member: person.id },
    props: { person },
  }));
}

const { person } = Astro.props;
---
<h1>{person.name}</h1>
<p>{person.role}</p>

Imports are hoisted, so they’re available inside getStaticPaths(). Variables declared in the frontmatter are not. The same isolation applies to the Astro global: using Astro.url or Astro.props inside the function fails, as described in the Astro global in getStaticPaths fix.

Params must be strings

Route parameters become parts of a URL, so Astro only accepts strings, or undefined for rest parameters. A number triggers “Invalid route parameter returned by getStaticPaths().”:

// Fails: id is a number
return items.map((item) => ({ params: { id: item.id } }));

// Works
return items.map((item) => ({ params: { id: String(item.id) } }));

You also need a key for every bracketed segment in the file name. A file at src/pages/[lang]/[slug].astro needs both lang and slug in every params object, or you’ll get the missing params error covered in the missing params fix.

Generating pages from a content collection

This is the most common use. Each entry in a collection becomes a page:

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

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

const { post } = Astro.props;
const { Content } = await render(post);
---
<article>
  <h1>{post.data.title}</h1>
  <Content />
</article>

getStaticPaths() can be async, so you can await collection queries or fetch() calls inside it. Passing the whole post as a prop means the page body doesn’t query the collection again. The content collections guide explains getCollection() and filters.

Rest parameters for nested paths

Use [...name] when a single parameter should cover several URL segments, such as docs with folders:

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

export async function getStaticPaths() {
  const docs = await getCollection('docs');
  return docs.map((doc) => ({
    params: { slug: doc.id === 'index' ? undefined : doc.id },
    props: { doc },
  }));
}

const { doc } = Astro.props;
const { Content } = await render(doc);
---
<Content />

An entry with id guides/install becomes /docs/guides/install/. Returning undefined for a rest parameter matches the route’s root, so the index entry renders at /docs/. This only works with rest parameters; a normal [slug] can’t be empty.

Fetching data from an API at build time

Data doesn’t have to be local. Anything you can fetch at build time works:

---
// src/pages/releases/[tag].astro
export async function getStaticPaths() {
  const res = await fetch('https://api.github.com/repos/withastro/astro/releases?per_page=10');
  const releases: Array<{ tag_name: string; name: string; body: string }> = await res.json();

  return releases.map((release) => ({
    params: { tag: release.tag_name },
    props: { release },
  }));
}

const { release } = Astro.props;
---
<h1>{release.name}</h1>
<pre>{release.body}</pre>

The request runs once per build, not once per visitor. When the source changes, rebuild the site, usually from a CMS webhook or a scheduled job. For sources you use across many pages, a content layer loader is a cleaner home for the fetch; see content layer loaders.

Pagination with paginate()

getStaticPaths() receives a helper object. Its paginate() function splits an array into numbered pages:

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

export const getStaticPaths = (async ({ paginate }) => {
  const posts = (await getCollection('blog')).sort(
    (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
  );
  return paginate(posts, { pageSize: 10 });
}) satisfies GetStaticPaths;

const { page } = Astro.props;
---
<ul>
  {page.data.map((post) => <li><a href={`/blog/${post.id}/`}>{post.data.title}</a></li>)}
</ul>
{page.url.prev && <a href={page.url.prev}>Newer posts</a>}
{page.url.next && <a href={page.url.next}>Older posts</a>}

That builds /blog/, /blog/2/, /blog/3/ and so on. The page prop includes data, currentPage, lastPage, total and url.prev, url.next, url.first and url.last. The same helper object also exposes routePattern, the route’s pattern string such as /blog/[...page], which is handy in shared helpers. The Astro pagination guide covers numbered links and nested pagination, such as per-tag archives.

Typing getStaticPaths with TypeScript

Annotating with satisfies GetStaticPaths checks the return shape while keeping precise types. Then infer the page’s props and params from it:

---
// src/pages/team/[member].astro
import type { GetStaticPaths, InferGetStaticParamsType, InferGetStaticPropsType } from 'astro';
import { team } from '../../data/team';

export const getStaticPaths = (() => {
  return team.map((person) => ({
    params: { member: person.id },
    props: { person },
  }));
}) satisfies GetStaticPaths;

type Params = InferGetStaticParamsType<typeof getStaticPaths>;
type Props = InferGetStaticPropsType<typeof getStaticPaths>;

const { member } = Astro.params as Params;
const { person } = Astro.props as Props;
---
<h1>{person.name}</h1>

Declaring type Props in the component also types Astro.props automatically, so the cast on that line is optional. Your editor now knows person.role exists and flags typos.

getStaticPaths and on-demand rendering

getStaticPaths() only applies to prerendered routes. If a page is rendered on demand, with an adapter installed and export const prerender = false, Astro doesn’t build a list in advance. The page reads parameters from the request instead:

---
// src/pages/orders/[id].astro
export const prerender = false;

const { id } = Astro.params;
const res = await fetch(`https://api.example.com/orders/${id}`);
if (!res.ok) return Astro.redirect('/404/');
const order = await res.json();
---
<h1>Order {order.number}</h1>

Use static paths when the list of pages is known at build time, which covers blogs, docs, product catalogs and portfolios. Use on-demand rendering when pages depend on user data or change faster than you can rebuild. The rendering mode guide helps you choose. For very large sites, Astro 7.4 added experimental parallel prerendering, covered in the parallel prerendering tip.

How Astro themes use getStaticPaths

Look inside almost any content-driven Astro theme and you’ll find the same handful of dynamic routes: blog/[id].astro, blog/[...page].astro, tags/[tag].astro, and for portfolios, work/[slug].astro. Each one is a short getStaticPaths() over a collection, which makes these routes easy to follow and extend. If you want to see that structure in a finished site, the Astro portfolio themes are a good place to look, and the pages docs explain how routes are organized. The official routing reference documents every option.

FAQ

What does getStaticPaths do in Astro?

It tells Astro which pages a dynamic route should generate at build time. The function returns an array where each item has params for the URL segments and optional props for page data. Astro renders one static HTML page per item.

Is getStaticPaths required in Astro?

Only for dynamic routes (file names with brackets) that are prerendered, which is the default. Static routes like about.astro don’t need it, and routes rendered on demand with prerender = false don’t use it.

Can getStaticPaths be async in Astro?

Yes. Declare it async and await anything you need, such as getCollection() or fetch(). It runs once per route at build time, so slow requests make the build slower but don’t affect visitors.

Why can’t I access variables inside getStaticPaths?

getStaticPaths() runs in its own scope before the component’s frontmatter executes, so top-level variables and the Astro global aren’t available. Put the data inside the function, or import it from a separate module, since imports are available.

What is the difference between params and props in getStaticPaths?

params defines the URL: each key fills a bracketed segment in the file name and must be a string. props passes any extra data to the page through Astro.props, which saves fetching it again while rendering.