Fix: Invalid Value Returned by getStaticPaths in Astro

Error message:
Invalid value returned by getStaticPaths.
Routing & Pages 2025-01-25

What Causes This Error?

This error occurs when getStaticPaths() returns something other than an array. The function must return an array of path objects, even if it’s empty.

The Problem

---
// ❌ Returns undefined (no return statement)
export function getStaticPaths() {
  const posts = fetchPosts();
}

// ❌ Returns an object instead of array
export function getStaticPaths() {
  return { params: { slug: 'post-1' } };
}

// ❌ Returns null
export function getStaticPaths() {
  return null;
}

// ❌ Returns a string
export function getStaticPaths() {
  return 'post-1';
}
---

The Fix

Return an Array

---
// ✅ Always return an array
export function getStaticPaths() {
  return [
    { params: { slug: 'post-1' } },
    { params: { slug: 'post-2' } },
  ];
}
---

Empty Array for No Pages

---
// ✅ Empty array is valid
export function getStaticPaths() {
  return [];
}
---

With Async/Await

---
// ✅ Async function returning array
export async function getStaticPaths() {
  const posts = await fetchPosts();
  return posts.map((post) => ({
    params: { slug: post.slug },
  }));
}
---

Common Scenarios

Forgetting Return Statement

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

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

Conditional Returns

---
// ❌ Might return undefined
export async function getStaticPaths() {
  const posts = await fetchPosts();
  if (posts.length > 0) {
    return posts.map((p) => ({ params: { slug: p.slug } }));
  }
  // No return here = undefined
}

// ✅ Always return array
export async function getStaticPaths() {
  const posts = await fetchPosts();
  if (posts.length === 0) {
    return [];
  }
  return posts.map((p) => ({ params: { slug: p.slug } }));
}
---

Single Path Wrapped in Array

---
// ❌ Single object, not array
export function getStaticPaths() {
  return { params: { slug: 'only-post' } };
}

// ✅ Wrap in array
export function getStaticPaths() {
  return [{ params: { slug: 'only-post' } }];
}
---

Using forEach Instead of map

---
// ❌ forEach returns undefined
export function getStaticPaths() {
  const paths = [];
  posts.forEach((post) => {
    paths.push({ params: { slug: post.slug } });
  });
  // Missing return!
}

// ✅ Use map or return the array
export function getStaticPaths() {
  return posts.map((post) => ({
    params: { slug: post.slug },
  }));
}
---

Quick Checklist

  • getStaticPaths must return an array
  • Include explicit return statement
  • Use .map() to transform data into path objects
  • Empty array [] is valid for zero pages
  • Don’t return single objects, strings, or null