Labs ICT
โญ Pro Login

getStaticPaths

getStaticPaths

The getStaticPaths function is used with dynamic routes when using static site generation. It tells Next.js which pages to generate at build time.

Think of it as a list of all possible pages your application might need. Without this list, Next.js wouldn't know which dynamic pages to create.

How It Works

When you have a dynamic route like [slug], Next.js needs to know all possible values of slug to generate the pages.

// app/blog/[slug]/page.js
export async function getStaticPaths() {
  const posts = await getAllPosts();
  
  const paths = posts.map(post => ({
    params: { slug: post.slug },
  }));
  
  return {
    paths,
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  const post = await getPost(params.slug);
  
  return {
    props: {
      post,
    },
  };
}

export default function BlogPost({ post }) {
  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  );
}

The paths array contains all the combinations of parameters that should be pre-rendered.

The Fallback Option

The fallback option controls what happens when a user requests a page that wasn't pre-rendered:

false: Shows a 44 for pages not in the paths array.

true: Shows a loading state while generating the page on-demand.

'blocking': Waits for the page to be generated and shows it directly.

export async function getStaticPaths() {
  return {
    paths: [
      { params: { slug: 'first-post' } },
      { params: { slug: 'second-post' } },
    ],
    fallback: 'blocking',
  };
}

With fallback: 'blocking', requesting /blog/third-post will generate it on-demand and cache it for future requests.

Combining with ISR

You can combine getStaticPaths with ISR for the best of both worlds:

export async function getStaticPaths() {
  const posts = await getAllPosts();
  
  const paths = posts.map(post => ({
    params: { slug: post.slug },
  }));
  
  return {
    paths,
    fallback: 'blocking',
  };
}

export async function getStaticProps({ params }) {
  const post = await getPost(params.slug);
  
  return {
    props: {
      post,
    },
    revalidate: 3600,
  };
}

This generates popular pages at build time, creates new pages on-demand, and regenerates all pages periodically.

Best Practices

Follow these guidelines when using getStaticPaths:

Pre-render popular pages: Generate the most visited pages at build time for optimal performance.

Use fallback wisely: Choose the right fallback strategy based on your content's nature.

Limit paths in development: In development mode, you can limit the number of paths generated to speed up builds.

Handle errors: Make sure your getStaticProps handles cases where the requested resource doesn't exist.

๐Ÿงช Quick Quiz

What is the purpose of getStaticPaths?