Open In App

Next.js Custom Error Page

Improve
Improve
Like Article
Like
Save
Share
Report

Next.js is a react-based framework that has all the building blocks necessary for a fully functional and interactive website/web app. Next.js is widely used due to its added advantages which include the creation of pre-rendered react websites. So many unique features are available in Next.js that have made many react developers learn Next.js. 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/

Creating Next.js application: 

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.

  • Open the terminal in your system.
  • Navigate to the directory where you want to create your Next.js application.
  • Type the following command to create a new Next.js application
npx create-next-app@latest gfg_custom_error_page
  • Note that ‘gfg_custom_error_page’ is the name of the application which is arbitrary.
  • Once you enter this command, you will be prompted to provide ‘yes/no’ answers to include certain features in your projects. You can use the arrow keys to shift between the ‘yes’ and ‘no’ and the ‘enter’ key to go to the next prompt.
  • This will automatically create the required file structure for your project. 
  • After creating the application, navigate to your project by typing the following command.
cd gfg_custom_error_page
  • Now we need to install all the dependencies listed in the package.json file by typing the following command.
npm install

File structure: Once your project has been created, the file structure of your project will look like this.

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’.

Example 1: 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.

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

404.js

Javascript




// 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: create a new file called ‘index.js’ in the pages directory.

index.js

Javascript




//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: 

custom 404 page

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. 

Example 2: 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’.

Prerequisite: 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. 

Step 1: create a new file called ‘about.js’ in the ‘pages’ directory

about.js

Javascript




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>
        );
    }
}


getInitialProps() method: This is a data fetching method in Next.js. In our code, it is defined as an asynchronous method. The URL to fetch is given as a parameter to the fetch() method and the response is converted to a JSON format using the method JSON (). 

render() method: A render() method is generally used in React to display data by creating a new component. In our case, the function contains a conditional statement to check the status code. 

To know more about the render() method, please visit this link.

The logic applied: 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

_error.js

Javascript




//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.

Error page displayed when data cannot be fetched.

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. 



Last Updated : 05 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads