Add custom 404 error page to your NextJS site

Want to add a custom, fun 404 error page like this my error page in your NextJS website ?

Let's get started

As seen in the Next.js blog, NextJS has a set of reserved pathnames like _app.js, _document.js and more.. each of them targeting a specific event.

One of these reserved paths is the 404.js/tsx file which targets the 404 error event. This is the file we will explore now.

By default Next gives us a decent 404 page, but it's often better to make a custom page for better UX.

image

Let's build our own page, start off by creating a 404.js or 404.tsx file under the pages directory of your NextJS application.

image

This file is like any other file under the pages directory only difference is that this page is rendered when the requested resource or the requested URL cannot be found on the server.

Export a React component from the 404.js or 404.tsx file, you can name the component anything. That's it you have created you custom 404 page. Whatever you export it from will be rendered on the page.

image

With the above code, your page looks something like this.

image

🤔 Now let's style this a little bit. Apply your CSS skills now or use a CSS framework like TailwindCSS

image

This is fine for a basic app but, let's ramp it up with a GIF. Embed a GIF from websites like https://giphy.com/. The code looks like this.

image

Now it all depends on how you style your page. Since, this page is not a main stream page it is not required to spend much time on styling but some decent styles would be good enough.

image

That's it now you have your own custom 404 error page for your NextJS application.

This doesn't end here, NextJS offers great customization you can also create a custom 500 error page in the exact same way. Simply create a file 500.js/tsx and export a React component with the message you want to display and you are done.

That's how you add custom error pages in NextJS. All the best for you custom error pages 😉

Until next time 👋