.map not a function error in getStaticPaths with dynamic routes
This is a common JavaScript error that happens when you're trying to call .map() on something that isn't an array. In the context of getStaticPaths, this usually means your Sanity query is returning data in an unexpected format.
The Problem
When you fetch data from Sanity for getStaticPaths, you need to ensure your query returns an array. The error "xxx.map is not a function" means the data you're trying to map over is either:
undefinednull- An object instead of an array
- Not yet loaded
The Solution
Here's the correct pattern for using .map() in getStaticPaths with Sanity queries:
export async function getStaticPaths() {
// Make sure your query returns an array of slug values
const paths = await client.fetch(
`*[_type == "post" && defined(slug.current)][].slug.current`
);
return {
paths: paths.map((slug) => ({ params: { slug } })),
fallback: true,
};
}Common Fixes
1. Check your query syntax
Make sure you're using the [] projection at the end to return an array:
// Good - returns an array of slugs
`*[_type == "post"][].slug.current`
// Bad - might return objects or undefined
`*[_type == "post"].slug.current`2. Add defensive coding
Always add a fallback in case the query returns nothing:
export async function getStaticPaths() {
const paths = await client.fetch(
`*[_type == "post" && defined(slug.current)][].slug.current`
);
// Ensure paths is an array before mapping
const safePaths = (paths || []).map((slug) => ({ params: { slug } }));
return {
paths: safePaths,
fallback: true,
};
}3. Debug what you're getting
Add a console.log to see what your query actually returns:
const paths = await client.fetch(`*[_type == "post"][].slug.current`);
console.log('Fetched paths:', paths, 'Type:', typeof paths);4. Handle multiple content types
If you're querying multiple types, make sure your query still returns an array:
const paths = await client.fetch(
`*[_type in ["post", "page"] && defined(slug.current)][].slug.current`
);The key is ensuring that whatever you're calling .map() on is actually an array. The defensive coding approach with (paths || []) is a good safety net that prevents the error even if your query returns unexpected data.
Show original thread6 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.