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.

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

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>

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

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, a job board for remote coders.

Picture of Nick Major.