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.
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
It’s cute to have a custom image on the 404 page.
- Select an appropriate image and put it into the
- Reference the image from within the
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
missingclass onto the
<body>tag when a 404 page is mounted and
- remove the
missingclass 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).
Go to a missing page and you’ll now see the 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.
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
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.