Start of Main Content

Ideally, your website’s users should never have to see an error page. Every page and its components should load correctly, so visitors can accomplish their goals quickly and easily. However, you can’t foresee every issue that could crop up on your site — errors are bound to happen. That’s why displaying error pages that describe exactly what’s wrong is essential to get users back on their journey to engage with your organization.

If you’re using Sitecore’s XM Cloud with NextJS and Vercel to power your website, thankfully Sitecore allows you to tell users what they need to know with custom error pages. You can create these custom error pages in the Pages Routing folder inside the Rendering folder. Here’s Sitecore’s official documentation on error pages in the JSS Next.js sample app.

Configuring customer error pages on the Sitecore side is done in your site tenant Settings.

A screenshot from Sitecore showing the Settings area where you can adjust error pages.

When the layout service responds with a 404 or a 500 error, then it will route the app to either the src/pages/404.tsx or src/pages/500.tsx.

If you open those files, you will find that to get the content for those pages, it makes a GraphQL call with the following query:

query ErrorPagesQuery($siteName: String!, $language: String!) {
  site {
    siteInfo(site: $siteName) {
      errorHandling(language: $language) {
        notFoundPage {
          rendered
        }
        notFoundPagePath
        serverErrorPage {
          rendered
        }
        serverErrorPagePath
      }
    }
  }
}

Make sure that the item name of the error pages does not contain spaces. If it does have spaces, the query won’t work. This is a Sitecore bug with the GraphQL implementation that I discovered and reported when working with a client. It’s tracked by Sitecore with the reference number 594686.

Need more help creating custom error pages in Sitecore XM Cloud?

Our Sitecore MVPs can walk you through how to create custom error pages for your website and answer any other Sitecore questions you have. 

Sitecore Custom Error Pages with Components That Use External Data

Custom error pages in Sitecore work well unless your error pages contain a component that relies on getting external data through GetStaticProps, which was the case for one of Velir’s clients. The Header and Footer contained components that relied on getting data with GetStaticProps. For example, while the 404 page was rendering, any component that used external data was empty.

If you review the GraphQL code it will only return data from the layout service, and it doesn’t include any external data.

So, I looked at how the [path].tsx file works and made some modifications on the 404.tsx.

I noticed that the 404 page didn’t have a componentsFactory, so I created one before 404 GetStaticProps returned the layout data. The componentsFactory also requires a route path, so I took it from the path of the error page that returns from the GraphQL query. This is needed so the factory can know what components the page requires. After these changes, my 404 page successfully rendered all components, including the ones that rely on external data.

You can check out the final code here:

import config from 'temp/config';
import {
  GraphQLErrorPagesService,
  SitecoreContext,
  ErrorPages,
  ComponentPropsContext,
} from '@sitecore-jss/sitecore-jss-nextjs';
import { SitecorePageProps } from 'lib/page-props';
import NotFound from 'src/NotFound';
import { componentBuilder } from 'temp/componentBuilder';
import Layout from 'src/Layout';
import { GetStaticProps } from 'next';
import { siteResolver } from 'lib/site-resolver';
import { sitecorePagePropsFactory } from 'lib/page-props-factory';

const Custom404 = (props: SitecorePageProps): JSX.Element => {
  if (!(props && props.layoutData && props.componentProps)) {
    return <NotFound />;
  }

  return (
    <ComponentPropsContext value={props.componentProps}>
      <SitecoreContext
        componentFactory={componentBuilder.getComponentFactory()}
        layoutData={props.layoutData}
      >
        <Layout layoutData={props.layoutData} headLinks={props.headLinks} />
      </SitecoreContext>
    </ComponentPropsContext>
  );
};


export const getStaticProps: GetStaticProps = async (context) => {
  const site = siteResolver.getByName(config.jssAppName);
  const errorPagesService = new GraphQLErrorPagesService({
    endpoint: config.graphQLEndpoint,
    apiKey: config.sitecoreApiKey,
    siteName: site.name,
    language: context.locale || config.defaultLanguage,
  });
  let resultErrorPages: ErrorPages | null = null;

  if (!process.env.DISABLE_SSG_FETCH) {
    try {
      resultErrorPages = await errorPagesService.fetchErrorPages();
    } catch (error) {
      console.log('Error occurred while fetching error pages');
      console.log(error);
    }
  }
  const paths = [
    `_site_${site.name}`,
    ...(resultErrorPages?.notFoundPagePath?.split('/')?.filter((x) => x.length > 0) ?? []),
  ];

  context.params = {
    path: paths,
  };
  const props = await sitecorePagePropsFactory.create(context);
  return {
    props: {
      componentProps: props.componentProps,
      headLinks: [],
      layoutData: resultErrorPages?.notFoundPage?.rendered || null,
    },
  };
};

export default Custom404;

With the code I’ve shared, you can create custom error pages in Sitecore XM Cloud with NextJS and Vercel that give users a clear idea of the error they’re receiving when they’re trying to access a page on your site that has components with external data. When users know what’s wrong it’s easier for them to figure out where to go next or who they can ask for help so they can continue engaging with your brand.

Need more help creating custom error pages in Sitecore XM Cloud? Contact us. Our Sitecore MVPs would be happy to help you and answer any other Sitecore questions you might have.

Published:

Latest Ideas

Take advantage of our expertise with your next project.