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.
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:
-
Fetch component props in the
getStaticPropsfunction of your error pages (such as404.tsxand500.tsx) using the following:RequestResponseprops.componentProps = await client.getComponentData(layout, context, components);NoteNext.js does not allow
getServerSidePropsorgetInitialPropsin error pages such as404.tsxand500.tsx. Using them causes the build to fail. Always usegetStaticPropsfor error pages. -
In your error page component:
-
Add an import for
ComponentPropsContext:RequestResponseimport { SitecorePageProps, ComponentPropsContext } from '@sitecore-content-sdk/nextjs'; -
Wrap the component with
ComponentPropsContextand passcomponentPropsas 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.