Open In App

Next.js Custom Error Page

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a custom error page in Next.js allows you to provide a better user experience when an error occurs, such as a 404 (Not Found) or a 500 (Server Error). Custom error pages can match your site's design and offer helpful information or navigation options. In this article, we will learn how to create custom error pages in Next.js.

Default error page in Next.js

The default error page in Next.js is the one that loads by default when an error occurs on the server or client side. It is usually not very appealing and has software jargons like status codes which are not user-friendly. This kind of information will only serve developers but not users.  

default 404 error page in Next.js

Custom error pages in Next.js

Just like handling exceptions in a programming language it is important to create custom error pages as well. The goal of custom error pages is to provide users with clear information about the error in a natural language and to assist them in taking further steps. The design of a custom error page can only be limited by the creativity of the developer. 

Note: Before getting into the practical part, please go through the below link to learn how to create your first Next.js project. https://www.geeksforgeeks.org/next-js-introduction/

Prerequisite:

Node.js and npm(Node Package Manager) must be installed in your system. Node.js version 10.13 or later is required to create and run a Next.js application. You can download Node.js here.

Steps to Create Next.js App

Step 1: Create a Next.js project using the following command

npx create-next-app@latest gfg_custom_error_page

Step 2: Moveto the project directory

cd gfg_custom_error_page

Step 3: Now we need to install all the dependencies listed in the package.json file by typing the following command.

npm install

Project Structure:

file structure

Running the application: To run your application, enter the following command in the terminal

npm run dev

Your application can now be accessed by visiting the URL ("http://localhost:3000/") using a browser. This URL will point to the root of your application's domain, which is 'index.js'.

Custom error page for client-side error

Client-side errors occur due to mistakes made by clients such as searching for a wrong URL. The most common client-side error is the 'Page Not Found' error which corresponds to a status code of '404'. This error occurs when a user tries to visit a page that doesn't exist. In Next.js, this error occurs when there is no route for the page that the user tries to access. 

The easiest way to create a custom error page to handle 'the 404' error is to override the default '404' error page. You can do this by creating a javascript file named '404.js' in the 'pages' directory of your project. Thus when a 404 error occurs during an HTTP request, this page is loaded instead of the default error page.

Steps to override 404.js

Step 1: create a new file called '404.js' in the 'pages' directory.

JavaScript
// 404.js

// import section
import { Typography, Button } from '@mui/material'
import Link from 'next/link'
import React from 'react'

// creation of component
const PageNotFound = () => {
    return (
        //fragment to print custom error message
        <>
            <Typography variant='h5'>
                Sorry, this page is not 
                found in GeeksForGeeks !!!
            </Typography>
            {/* //button to return to home page   */}
            <Link href='/'><a>
                <Button variant='text'>Go to Home</Button></a>
            </Link>
        </>
    )
}
export default PageNotFound

In this code, we have used Material-UI for styling purposes. 

To install Material-UI for your project, run the code in your terminal where the current working directory is your project directory. 

npm install @material-ui/core

I have created a react component named 'PageNotFound' and included a simple customized text message inside it. I have also included a button and linked it to the root i.e, 'index.js'. 

Step 2: Modify the index.js in the pages directory.

JavaScript
// index.js

//import section
import { Box, Chip, Stack, Typography } from "@mui/material";
import Head from "next/head";
import Image from "next/image";
import Link from "next/link";

// Component
export default function Home() {
    return (
        <Box sx={{ marginBottom: 20 }}>
            <Head>
                <title>Next | Home</title>
                <meta name="keyword" content="home" />
            </Head>
            <Stack alignItems='center' justifyContent='center'>
                <Image src="/gfg-new-logo.png" width={500} 
                       height={250} margintop={20} />
                <Stack alignSelf='flex-start' spacing={2} mb={10}>
                    <Typography variant="h3">Hello Geeks!</Typography>
                    <Typography color="green">
                        Welcome to GeeksForGeeks!!! Let's learn about 
                        customizing error pages in Next.js.
                    </Typography>
                </Stack>
            </Stack>
        </Box>
    );
}

you can learn how to add styles to your website by clicking the following link:- https://www.geeksforgeeks.org/how-to-add-stylesheet-in-next-js/

Execution and Output: 


Explanation 

  • I have entered the wrong URL which is '"http://localhost:3000/wrong_page".
  • This triggers the '404.js' error page, customized by ourselves. 
  • Instead of loading the default 404 error page of Next.js, our custom 404 error page is loaded successfully. 

Custom error page for server-side error

Till now, we focused on 404 errors which is a major client-side errors. But what if an error occurs on the server side? Luckily, Next.js provides a way to customize error pages for server-side errors too. 

In the following example, we are going to deal with the most common server-side error, an error with the status code '500' which corresponds to the error message 'Internal Server Error'.

Inastall the Required Module:

To execute the upcoming example we need a module called 'isomorphic-unfetch'. You can install this in your application by navigating to your project directory and entering the following command in the terminal.

 npm i isomorphic-unfetch 

We need this module to fetch data on the 'about' page. 

In this example, I'm fetching user data from Git Hub through an API.: https://api.github.com/users/matrixangel1

user data from github

The URL 'https://api.github.com/users/matrixangel1', when given to the browser provides the user data in JSON format, where 'matrixangel1' is a valid user name. In this example, we are going to fetch the values of 'login' and 'avatar_url' to display the user name and display a picture that belongs to that user, correspondingly. 

Steps to handle server-side Error

Step 1: Create a new file called 'about.js' in the 'pages' directory

JavaScript
// about.js

import Layout from "../components/Layout";
import fetch from "isomorphic-unfetch";
import Error from './_error';
// import section
import { Component } from "react";

export default class About extends Component {
    static async getInitialProps() {
        // Fetching user info
        const res = await fetch("https://api.github.com/users/wrong_user");
        // Checking the status code of the retrieved url
        const statusCode = res.status > 200 ? res.status : false;
        const data = await res.json();

        return { user: data, statusCode };
    }

    render() {
        const { user, statusCode } = this.props;
        // Return error page if status code is greater than 200
        if (statusCode) {
            return <Error statusCode={statusCode} />;
        }
        // Display of user name and profile picture
        return (
            <Layout title="About">
                <p>{user.login}</p>
                <img src={user.avatar_url} alt="Reed" height="200px" />
            </Layout>
        );
    }
}

Explanation: The render() method will return the user data only if the value of the status code is greater than 200. This logic is based on the fact that the status code 200 denotes 'OK', a successful HTTP request, and any value which is greater than 200 usually denotes an error. 

Step 2: Create a new file called '_error.js' in the 'pages' directory

JavaScript
_error.js

//import section
import Layout from "../components/Layout";

export default ({ statusCode }) => (
    <Layout title="Error!!!">
        {/* //checking the status code */}
        {statusCode
            ? 'user data could not be loaded '
            : 'page not found sorry!'}
    </Layout>
);

'_error.js' performs the exact same thing as the 404.js page except these are used to override the error component used to handle errors with status code 500. In short, '404.js' is used for customizing the error page for client-side errors while '_error.js' does the same for server-side errors. 

Execution and Output:

Case 1: fetching succeeds 

When we enter the correct URL to fetch data ("https://api.github.com/users/matrixangel1") in the fetch() method, the output will resemble the following image:-

fetched data from the correct URL

Case 2: fetching fails (_error.js loads)

If you enter an incorrect URL such as "https://api.github.com/users/wrong_user", you will get the following output.


Explanation:

  • The page fails to fetch data from API since the entered URL is incorrect. 
  • Instead of showing a stack trace of the error, Next.js loads the '_error.js' page which contains our custom error message. 
  • Thus, a custom error page is successfully built to respond to server-side errors. 

Conclusion

Hence, Next.js offers both primitive and advanced ways to develop custom error pages. Error pages for commonly occurring errors can be easily handled by overriding the default error page. Next.js provides options to handle both client-side and server-side errors. I hope that you can now feed your users with appealing error pages instead of freaky technical jargons. 


Next Article

Similar Reads