Blog>
Snippets

Advanced Route Loading with getStaticPaths

Show how to use getStaticPaths for advanced static generation, including fallback handling and pre-rendering dynamic routes.
export async function getStaticPaths() {
  // Fetch the list of items from your API or file system:
  const items = await fetchItems();

  // Generate paths with `id` parameter for each item
  const paths = items.map(item => ({
    params: { id: item.id.toString() },
  }));

  return {
    // Pre-render only these paths at build time
    paths,
    // Enable fallback for the other paths and serve a static shell
    fallback: true, // can also be 'blocking' for SSR
  };
}
This getStaticPaths function fetches a list of items and generates static paths for them, enabling fallback for non-pre-rendered routes. If 'fallback' is set to 'true', a static shell is shown while the page is being generated. If set to 'blocking', the user waits for the server-side rendered version of the page.
export async function getStaticProps({ params }) {
  // Fetch data for the page using params.id
  const itemData = await fetchItemData(params.id);

  // If the data could not be found, return 404
  if (!itemData) {
    return { notFound: true };
  }

  // Provide the data to the page via props
  return {
    props: { itemData },
    // Revalidate at most every 10 seconds
    revalidate: 10,
  };
}
The getStaticProps function fetches data for each pre-rendered path. If the data is not found for a given path, the function returns a 404. It sets revalidation time, allowing the page to update its static content every 10 seconds.
export default function ItemPage({ itemData }) {
  const router = useRouter();

  // If the page is not yet generated and fallback is true,
  // this will be shown initially
  if (router.isFallback) {
    return <div>Loading...</div>;
  }

  // Render the item data
  return <div>
    <h1>{itemData.name}</h1>
    <p>{itemData.description}</p>
  </div>;
}
The ItemPage component accepts the item data as props. It uses the useRouter hook to determine if the page is in fallback state and displays a loading message in that case. Once the page is statically generated, it renders the data.