Next.js Custom Error Page
Last Updated :
25 Jul, 2024
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.jsCustom 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 structureRunning 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 githubThe 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 URLCase 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.Â
Similar Reads
How to create a Custom Error Page in Next.js ?
Creating a custom error page in Next.js allows you to provide a better user experience by customizing the appearance and messaging of error pages like 404 and 500.In this post we are going to create a custom error page or a custom 404 page in a Next JS website.What is a custom error page?The 404 pag
2 min read
Next.js Custom Server
Next.js Custom Server allows advanced customization by overriding default behavior. It enables tailored server-side logic, middleware integration, and API route handling, offering flexibility beyond standard Next.js configurations.Next.js Custom ServerA custom server in Next.js is a Node.js script t
2 min read
Custom Messages in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.O
11 min read
Next.js Custom Document
A custom document is a functionality that allows gives us access to setting up the metadata globally giving us an upper hand in search engine optimization, it can also be used to give styling globally as demonstrated in the later part. In this article, we will learn how to create the _document.js; w
3 min read
Next.js File Conventions: page.js
Next.js File Conventions are practices and rules for organizing files in a Next.js application to manage routing and components efficiently. In these conventions, the page.js file represents a specific route in the application, where each file in the pages or app directory corresponds to a route. Th
4 min read
Spring Boot - Custom Error Pages
In web applications, a generic error page is typically displayed when a server error occurs or when a user tries to access a non-existent page. These default pages may not be user-friendly and can lead to a poor user experience. Spring Boot allows us to customize these error pages to make them more
5 min read
TypeScript Custom Errors in RESTful API
In this article, we will explore the importance of using custom error handling in TypeScript for RESTful APIs. We will begin by highlighting the problem statement, followed by demonstrating the problem with code examples and error outputs. Finally, we will present a solution approach using custom er
5 min read
Next JS File Conventions: error.js
Next.js manages file conventions to perform error handling within your application. By using error.js, you can define how your application responds to errors at the page or application level. This file allows you to create custom error pages that handle exceptions gracefully and provide users with a
4 min read
Underscore.js _.isError() Function
Underscore.js is a library in javascript that makes operations on arrays, string, objects much easier and handy. _.isError() function is used to check whether the given object is javascript Error Object or not. Note: It is very necessary to link the underscore CDN before going and using underscore f
2 min read
Python Django Handling Custom Error Page
To handle error reporting in Django, you can utilize Django's built-in form validation mechanisms and Django's error handling capabilities. In this article, I'll demonstrate how to implement error handling. If there are errors in the form submission, the user will be notified of the errors. Required
4 min read