Next.js article thumbnail image.

The Next.js framework has a built-in way for handling 404 errors (i.e. "Page Not Found") that occur on your website. But to add a custom layout and styling to that page, you'll need to create a /pages/404.js file.

When that error occurs, Next.js will render that page instead of the default page it would otherwise automatically generate.

You can read more about Next.js custom error pages in their documentation.

In this article, we'll walk you through how to create a custom 404 error page for your Next.js website.

Let's get to it!

To begin, navigate to the /pages directory inside your Next.js application folder:

cd pages

Inside that directory, create a new file named 404.js:

touch 404.js

Then, add this code to the file:

import { Component } from "react"

export default class extends Component {
  render () {
    return (
      <div style={{padding: "15px"}}>
        <span>404 - Page Not Found.</span>
      </div>
    )
  }
}

When your Next.js application encounters a 404 error, it will display this 404 - Page Not Found. message instead of its default 404 page.

To test this page, you'll need to open your browser to a page on your website that doesn't exist.

As an example, open your browser to this page: http://localhost:3000/fasdf.

If your website doesn't have a "/fasdf" URL endpoint, a 404 - Page Not Found. message should be displayed on the page indicating that the page couldn't be found.

Custom Error Page For A Next.js Website

Your website is now equipped to display a custom page for any 404 errors it encounters.

That was the last step in this article.

Thanks for reading and happy coding!

About the author

Hi, I'm Nick Major. I'm a software developer from Wisconsin, United States.

I create free and premium courses, have published hundreds of informational coding articles, and am currently a Frontend Software Engineer at RoundingWell.

You can read more about me here.

Picture of Nick Major.