0
0
NextjsConceptBeginner · 3 min read

What is getStaticPaths in Next.js: Explanation and Example

getStaticPaths is a Next.js function used to specify dynamic routes that should be pre-rendered at build time. It returns a list of paths that Next.js uses to generate static pages for each route. This helps create fast, SEO-friendly pages for dynamic content.
⚙️

How It Works

Imagine you have a website with many pages, like a blog with posts. Each post has its own page, but you don't want to create each page manually. getStaticPaths helps by telling Next.js which pages to build ahead of time.

When you use getStaticPaths, you return a list of paths (like URLs) that represent each page you want to create. Next.js then generates these pages during the build process, so when someone visits, the page loads instantly without waiting for the server.

This is like preparing all your meals in advance for a party, so guests get served quickly instead of waiting for cooking.

💻

Example

This example shows how to use getStaticPaths with a dynamic blog post page. It pre-builds pages for posts with IDs 1 and 2.

javascript
export async function getStaticPaths() {
  return {
    paths: [
      { params: { id: '1' } },
      { params: { id: '2' } }
    ],
    fallback: false
  };
}

export async function getStaticProps({ params }) {
  return {
    props: {
      postId: params.id
    }
  };
}

export default function Post({ postId }) {
  return <h1>Post ID: {postId}</h1>;
}
Output
<h1>Post ID: 1</h1> or <h1>Post ID: 2</h1> depending on the URL
🎯

When to Use

Use getStaticPaths when you have dynamic routes that need to be pre-rendered as static pages. This is great for blogs, product pages, or any content that doesn't change often but has many unique pages.

It improves performance and SEO because pages are ready at build time. Avoid it if your data changes very frequently or you have too many pages, as rebuilding can be slow.

Key Points

  • getStaticPaths defines which dynamic routes to pre-build.
  • It returns an object with paths and fallback keys.
  • paths is an array of route parameters.
  • fallback: false means only specified paths are built; others show 404.
  • Works with getStaticProps to fetch data for each page.

Key Takeaways

getStaticPaths tells Next.js which dynamic pages to build at compile time.
It improves page speed and SEO by pre-rendering pages before users visit.
Use it for dynamic routes with stable data like blogs or product pages.
Returns paths array and fallback setting to control behavior.
Works together with getStaticProps to provide data for each page.