← coderrocketfuel.com

Create A Custom 404 Error Page For Your Next.js Website

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.

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 Next.js Website

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