← coderrocketfuel.com

Create Custom 500 Error Pages For A Next.js Website

The Next.js framework has built-in ways for handling 500 errors (i.e. "Server Side Error") that occur on your website. But to add a custom layout and styling to that page, you'll need to create a /pages/_error.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.

We'll walk you through how to create a custom 500 error page for your Next.js website.

Let's get started!

First, navigate to the /pages directory inside your Next.js application:

cd pages

And create a new file named _error.js:

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.

In development mode when a 500 error occurs, you’ll get an error with the call stack to know where the error originated from instead of this page. Therefore, this page will only be displayed in production.

But using the provided code, the page should look like the image below.

Custom 500 Error Page For A Next.js Website

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