How to use Content Driven Error Pages
NextJs has its own handling of 404 and 500 pages. Because of this you will see NextJs build errors if you have a route for /404
in Sitecore. Let's look at how we can use the Custom Error Page functionality of NextJs to use content in Sitecore.
#
Sitecore Pages for Not Found and Server ErrorThere are two types of error which NextJs can handle statically. They are "Not Found" (404) and Server (500) errors.
Create a page for each of these, let's call them /notfound
and /servererror
. This is where the content editor can control the content of these pages. Both these pages should be included in the Uniform page map.
#
NextJs Custom Pages#
404Create a pages/404.tsx file which looks like the following example.
import React from 'react';
// Pageimport Page from './[[...slug]]'
export async function getStaticProps({ params }) { const asPath = '/notfound'; const props = await getNextPageProps({ asPath }); return { props };}
export default Page;
In this example we take the default
export from the [[...slug]].tsx
file which will be the Page React Component and we reuse it.
We then have a customised getStaticProps
which is hard-coded to fetch props for the /notfound
page path.
#
500Create a pages/500.tsx file and use the same code snippet, just substituting "notfound" for "servererror".
import React from 'react';
// Pageimport Page from './[[...slug]]'
export async function getStaticProps({ params }) { const asPath = '/servererror'; const props = await getNextPageProps({ asPath }); return { props };}
export default Page;
#
TroubleshootingIf you have named your Sitecore pages /404
and /500
you will probably see a nextjs build error because you cannot include these paths in getStaticPaths
.
You have two options.
- Change the Sitecore pages to something else. For example
/_404
or/notfound
. - Filter out the "404" and "500" paths as seen in the following snippet:
// Using Automatic Static Optimizationexport async function getStaticPaths() { const { getStaticPaths } = await import('@uniformdev/next-server'); const paths = await getStaticPaths(); return { paths: paths .filter(({ params }) => { const p = String(params.slug[0]) return !['404', '500'].includes(p) }), }}