09 Feb 2024




Intermediate

getStaticPaths is a function used to generate paths for pages with dynamic routes during Static Site Generation (SSG). It allows developers to specify which dynamic paths should be pre-rendered at build time, enabling the creation of static HTML files for improved performance and SEO.

Key points about getStaticPaths:

  • Dynamic Routes: Dynamic routes allow you to create pages dynamically based on data. For instance, in a blog application, you might have dynamic routes for individual blog posts like /posts/1, /posts/2, etc., where 1, 2, etc., are dynamic parameters representing the post IDs.

  • Pre-rendering: Next.js allows you to pre-render pages at build time using SSG. With SSG, pages are generated as static HTML files during the build process, which can then be served to users directly from a CDN for improved performance and SEO.

  • getStaticPaths Function: This function is implemented within a page file (e.g., [id].js for dynamic routes in the pages directory). It returns an object with two properties:

    • paths: An array of objects representing the dynamic paths that Next.js should pre-render.
    • fallback: A boolean or string value that determines the behavior when a requested path doesn't match any of the pre-defined paths.
  • Generating Paths Dynamically: Inside getStaticPaths, you typically fetch data from an external source (like a database or an API) to determine the dynamic paths that need to be pre-rendered. You then return an array of objects containing the params key with the dynamic parameter values.

  • Fallback Behavior: The fallback property in the object returned by getStaticPaths controls what happens when a requested path doesn't match any of the pre-defined paths.

    • fallback: false: Next.js returns a 404 page if the requested path doesn't match any of the pre-defined paths.
    • fallback: true: Next.js will attempt to generate the requested path on-demand, allowing for dynamic content. Users might initially see a loading state.
    • fallback: 'blocking': Similar to true, but Next.js will serve a static page immediately while it generates the requested page in the background.

getStaticPaths Return Values:

The getStaticPaths function returns an object with the following required properties:

1. paths:

  • Determines which paths will be pre-rendered statically.
  • Contains an array of objects, each specifying the parameters for dynamic segments in the URL.
  • Parameters must match those used in the page name.
  • Paths can be normalized, and locale information can be included if using i18n.

2. fallback: false:

  • If set to false, paths not returned by getStaticPaths result in a 404 page.
  • Useful for a small number of manageable paths or when new data is infrequently added.
  • Requires a rebuild (next build) to add new paths.

3. fallback: true:

  • If set to true, paths not generated at build time serve a "fallback" version on the first request.
  • Subsequent requests to the same path serve the fully generated page.
  • Useful for a large number of dynamic paths with potentially infrequent updates.
  • Suitable for scenarios where a loading indicator or skeleton component can be displayed initially.

4. fallback: 'blocking':

  • Similar to fallback: true, but new paths wait for HTML generation, behaving like server-side rendering (SSR).
  • Provides a seamless transition without a flash of loading/fallback state.
  • Requires a rebuild for updates but efficiently caches the generated HTML for subsequent requests.
  • Revalidate: Optionally, you can provide a revalidate key in the returned object to specify how frequently Next.js should re-generate the paths.

Use Cases:

  • fallback: false: Small number of manageable paths, infrequent updates.
  • fallback: true: Large number of dynamic paths with potentially infrequent updates.
  • fallback: 'blocking': Efficient SSR-like behavior with a seamless transition.

TypeScript example of using getStaticPaths in Next.js:

In Next.js, getStaticPaths is used to generate static paths for pages with dynamic routes. When using dynamic routes, you often encounter scenarios where not all possible paths are known at build time. Next.js provides the fallback key within the getStaticPaths function to handle these scenarios.

Consider a scenario where you have a blog with posts fetched from an API. Each post has a unique ID, and you want to pre-render the pages for each post.

First, let's define the types:

// types.ts

type Post = {
  id: string;
  title: string;
  content: string;
};

type Params = {
  id: string;
};

Now, let's implement the getStaticPaths function with different fallback options:

// pages/posts/[id].tsx

import { GetStaticPaths, GetStaticProps } from 'next';
import { fetchAllPostIds, fetchPostById } from '../../lib/api';
import { Post, Params } from '../../types';

const PostPage: React.FC<{ post: Post }> = ({ post }) => {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
};

export const getStaticPaths: GetStaticPaths<Params> = async () => {
  // Fetch all post IDs from an API
  const postIds = await fetchAllPostIds();

  // Generate paths based on post IDs
  const paths = postIds.map((id) => ({ params: { id } }));

  // Return the paths along with fallback behavior
  return {
    paths,
    // 'false' means pages that don't have paths will result in a 404 page.
    // 'true' means Next.js will render the page on-demand if the path is not pre-rendered.
    // 'blocking' means Next.js will render the page on-demand in the background, returning a fallback immediately.
    fallback: false,
  };
};

export const getStaticProps: GetStaticProps<{ post: Post }, Params> = async ({ params }) => {
  // Fetch post data based on the ID from params
  const post = await fetchPostById(params.id);

  return {
    props: {
      post,
    },
  };
};

export default PostPage;

Explanation:

  1. getStaticPaths Function:

    • In getStaticPaths, we fetch all post IDs from an API using fetchAllPostIds.
    • We then generate paths based on these IDs and return them as an array of objects with the params key.
    • We also specify the fallback behavior:
      • fallback: false: This means that any paths not returned by getStaticPaths will result in a 404 page.
      • fallback: true: This means that Next.js will attempt to render the page on-demand if the path is not pre-rendered.
      • fallback: 'blocking': This means Next.js will render the page on-demand in the background, returning a fallback immediately.
  2. getStaticProps Function:

    • This function fetches the post data based on the ID provided in the params.
    • It returns the post data as props to the component.

In this example, fallback controls the behavior for paths that are not pre-rendered. Depending on the value of fallback, Next.js behaves differently:

  • With fallback: false, only the paths returned by getStaticPaths will be accessible.
  • With fallback: true, Next.js will attempt to render the page on-demand if the path is not pre-rendered.
  • With fallback: 'blocking', Next.js will render the page on-demand in the background, returning a fallback immediately.

These options provide flexibility depending on your application's needs and data availability during the build process.

next.js
getstaticpaths