Blog>
Snippets

Dynamic Route Caching with getStaticProps and getStaticPaths

Show how to pre-render dynamic routes with getStaticProps and getStaticPaths and revalidate them with the 'revalidate' feature for caching.
export async function getStaticPaths() {
  // Get the list of possible dynamic routes
  const paths = await fetchMyDynamicRoutes();

  return {
    paths,
    fallback: 'blocking' // or 'true' for client-side rendering on-demand
  };
}
This getStaticPaths function fetches a list of dynamic routes that need to be pre-rendered at build time. The 'paths' returned are the paths that will be statically generated. The 'fallback' value controls the behavior of the server for paths not generated at build time.
export async function getStaticProps(context) {
  // Get the data for this dynamic route
  const data = await fetchDataForDynamicRoute(context.params);

  return {
    props: { data },
    revalidate: 10 // Time in seconds after which a page re-generation can occur
  };
}
This getStaticProps function fetches data for a specific dynamic route given a context that includes the dynamic parameters. The function returns an object with props containing the data to render the page and a 'revalidate' property. This property enables Incremental Static Regeneration, telling Next.js to revalidate the page every 10 seconds.
<!-- pages/[dynamicRoute].js -->
// ... Your other imports

function DynamicPage({ data }) {
  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  );
}

export default DynamicPage;
This is a simple React component for a dynamically routed page, where '[dynamicRoute]' is the file name to denote a dynamic segment in the URL. The component receives 'data' through props, which is used to render the page with the title and content.