Creating a Custom 404 Page in Next.js | Lec-7 | Complete Next.js Course

Posted by


In this tutorial, we will learn how to create a custom 404 page in Next.js. The 404 page is displayed when a user tries to access a page that does not exist. We will customize the appearance of the 404 page to match our website’s design and provide a better user experience.

Step 1: Create a custom 404 page component

First, create a new file named 404.js in the pages directory of your Next.js project. This file will represent the custom 404 page component. You can also name this file error.js if you prefer.

In this file, you can add the following code to create a simple custom 404 page:

import Link from 'next/link';

const Custom404 = () => {
  return (
    <div>
      <h1>404 - Page Not Found</h1>
      <Link href="/">
        <a>Go back to home</a>
      </Link>
    </div>
  );
};

export default Custom404;

You can customize this component by adding images, illustrations, or any other elements to make it more visually appealing.

Step 2: Configure Next.js to use the custom 404 page

By default, Next.js uses a built-in 404 page when a page is not found. To use our custom 404 page, we need to add a custom error handler to our Next.js app.

Create a new file named _error.js in the pages directory of your Next.js project. Add the following code to create the custom error handler:

import React from 'react';
import Custom404 from './404';

const ErrorPage = () => <Custom404 />;

export default ErrorPage;

This code tells Next.js to render our custom 404 page component when any error occurs. You can also add custom error handling logic in this file if needed.

Step 3: Add a custom 404 page style

To style the custom 404 page, you can create a new CSS file named 404.module.css in the styles directory of your Next.js project. Add the following CSS code to style the custom 404 page:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

h1 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 20px;
}

a {
  color: #0070f3;
  text-decoration: none;
  margin-top: 20px;
}

You can customize this CSS code to match your website’s design. Don’t forget to import this CSS file in your custom 404 page component.

Step 4: Test the custom 404 page

To test the custom 404 page, run your Next.js app and try to access a non-existent page. You should see the custom 404 page that you created, with the styles applied.

Congratulations! You have successfully created a custom 404 page in Next.js. You can further customize the page by adding more content, animations, or interactive elements to enhance the user experience. Thank you for following along in this tutorial!