Enable component-level data fetching for error pages in Next.js apps

Error pages (such as 404.tsx and 500.tsx) now support component-level data fetching in the Next.js starter template. This allows error pages to fetch and render component-specific data like regular pages.

Important

Component-level data fetching for error pages is only available in Content SDK versions 1.1.0 and later.

By enabling component-level data fetching, components on error pages fetch their own data using the same mechanisms as components on standard pages, instead of relying on static content.

To enable component-level data fetching for error pages in your Next.js apps:

  1. Fetch component props in the getStaticProps function of your error pages (such as 404.tsx and 500.tsx) using the following:

    RequestResponse
    props.componentProps = await client.getComponentData(layout, context, components);
    Note

    Next.js does not allow getServerSideProps or getInitialProps in error pages such as 404.tsx and  500.tsx. Using them causes the build to fail. Always use getStaticProps for error pages.

  2. In your error page component:

    • Add an import for ComponentPropsContext:

      RequestResponse
      import { SitecorePageProps, ComponentPropsContext } from '@sitecore-content-sdk/nextjs';
    • Wrap the component with ComponentPropsContext and pass componentProps as shown:

      RequestResponse
      ...
      const Custom404 = (props: SitecorePageProps): JSX.Element => {
        return (
          <ComponentPropsContext value={props.componentProps || {}}>
              ...
          </ComponentPropsContext>
        )
      };

This enables component-level data fetching for your error pages and ensures that the error pages also have access to the same granular data-fetching capabilities as the rest of your application.

Do you have some feedback for us?

If you have suggestions for improving this article,