Next.js article thumbnail image.

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.

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

Advertisement
Find Remote Coding Jobs
RemotelyWeCode.com curates the best remote software development jobs from startups and companies around the world.
Find Jobs

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.

That was the last step in this article.

Thanks for reading and happy coding!

About the author

Hey, I'm Nick, a software developer from Wisconsin, USA.

My latest course Build A Hacker News Clone walks you through how to build a clone of Hacker News using React.js, Node.js, MongoDB, & friends.

I also built and run RemotelyWeCode.com, a job board for remote coders.

Picture of Nick Major.