← coderrocketfuel.com

Create Custom Error Pages For A Next.js Website

The Next.js framework has built-in ways for handling 404, 500, and other errors that may occur on your website. But to add custom layout and styling to those pages, you'll need to create both a /pages/404.js and /pages/_error.js file.

When one of those errors occur, Next.js will render that page instead of the default page it would otherwise automatically generate.

The /pages/404.js file will handle all 404 related errors. And the /pages/_error.js file will handle 500 type errors.

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

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

Let's get these pages created.

Table Of Contents

404 Error Page

First, we'll build the page for handling 404 errors.

Navigate to your /pages directory:

cd pages

And 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. 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.

500 Error Page

We'll also create a custom error page for any 500 errors your website runs into.

To do this, we'll create an _error.js page similar to the 404.js page we just created in the last section.

First, navigate to your /pages directory and create a new file named _error.js:

cd pages && touch _error.js

Then, add this code to the file:

import { Component } from "react"

export default class extends Component {
  render () {
    return (
      <div style={{padding: "15px"}}>
        <span>An error occurred.</span>
      </div>
    )
  }
}

This code creates a page that will display an An error occurred. error message.

When your Next.js application encounters a 500 error, it will display this instead of its default error page.

Make sure you save the changes you made to your application.

That was the last step in this guide.