Custom 404 Page

Setting up a custom 404 page can add something special to your site. It provides you with the opportunity to do something memorable in the unfortunate event that a user asks for an unknown page.

🚀 TL;DR Show me the code. Look at the 16-custom-missing branch. This site is deployed here.

Layout

We want the layout of the 404 page to be consistent with the rest of the site, so import into 404.js the same Layout that’s being used in home.js and article.js.

Custom Image

It’s cute to have a custom image on the 404 page.

  1. Select an appropriate image and put it into the static/ directory.
  2. Reference the image from within the <Layout> in the NotFoundPage() component.

Custom Class

You might want to implement a different set of styles for the 404 page. One way to do this is to insert a specific class onto the <body> tag. This can be done using useEffect() in the NotFoundPage() component. This effect will

  • insert a missing class onto the <body> tag when a 404 page is mounted and
  • remove the missing class from the <body> tag when a 404 page is unmounted.

For the purpose of illustration we’ll use this class to center-align the text on the page (see screenshot below).

Get Lost

Go to a missing page and you’ll now see the custom 404 page.

Custom 404 page.

You can use https://httpstatus.io/ to check the status code associated with that URL and confirm that it is indeed a hard 404 (as opposed to a soft 404). This disctinction, hard versus soft 404, is very important for SEO purposes.

Checking status code on 404 page.

Troubleshooting

What if this setup doesn’t get you a 404 status code? If you are hosting your site on Netlify then there’s something else that you can do: create a static/_redirects file with the following contents:

/* /404/ 404
/* /404.html 404

When you build the site this will generate a _redirects file in the site root folder. Netlify will return a status code when a page is redirected to either /404/ or /404.html.

⚠️ Vercel is another hosting platform that returns a 404 status code for 404 pages. See this for how to set up your Gatsby site on Vercel.

Conclusion

A custom 404 page can be thought of as a nice-to-have: certainly not mandatory, but will make your site a little more slick and interesting (if done well). These are a few concrete reasons why it’s a good idea:

  • improved UX (your 404 page can make suggestions on how to find what the user was looking for)
  • branding consistency
  • engagement (it’s an opportunity to display humour and creativity) and
  • reduced bounce rate.

🚀 TL;DR Show me the code. Look at the 16-custom-missing branch. This site is deployed here.