404 Page
A 404 page may be accessed very often. Server-rendering an error page for every visit increases the load of the Next.js server. This can result in increased costs and slow experiences.
To avoid the above pitfalls, Next.js provides a static 404 page by default without having to add any additional files.
Customizing The 404 Page
To create a custom 404 page you can create a pages/404.js
file. This file is statically generated at build time.
// pages/404.js
export default function Custom404() {
return <h1>404 - Page Not Found</h1>
}
Note: You can use
getStaticProps
inside this page if you need to fetch data at build time.
500 Page
Server-rendering an error page for every visit adds complexity to responding to errors. To help users get responses to errors as fast as possible, Next.js provides a static 500 page by default without having to add any additional files.
Customizing The 500 Page
To customize the 500 page you can create a pages/500.js
file. This file is statically generated at build time.
// pages/500.js
export default function Custom500() {
return <h1>500 - Server-side error occurred</h1>
}
Note: You can use
getStaticProps
inside this page if you need to fetch data at build time.
More Advanced Error Page Customizing
500 errors are handled both client-side and server-side by the Error
component. If you wish to override it, define the file pages/_error.js
and add the following code:
function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} occurred on server`
: 'An error occurred on client'}
</p>
)
}
Error.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404
return { statusCode }
}
export default Error
pages/_error.js
is only used in production. In development you’ll get an error with the call stack to know where the error originated from.
Reusing the built-in error page
If you want to render the built-in error page you can by importing the Error
component:
import Error from 'next/error'
export async function getServerSideProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const errorCode = res.ok ? false : res.status
const json = await res.json()
return {
props: { errorCode, stars: json.stargazers_count },
}
}
export default function Page({ errorCode, stars }) {
if (errorCode) {
return <Error statusCode={errorCode} />
}
return <div>Next stars: {stars}</div>
}
The Error
component also takes title
as a property if you want to pass in a text message along with a statusCode
.
If you have a custom Error
component be sure to import that one instead. next/error
exports the default component used by Next.js.
Caveats
Error
does not currently support Next.js Data Fetching methods likegetStaticProps
orgetServerSideProps
._error
, like_app
, is a reserved pathname._error
is used to define the customized layouts and behaviors of the error pages./_error
will render 404 when accessed directly via routing or rendering in a custom server.
This documentation explains how you can handle development, server-side, and client-side errors.
Handling Errors in Development
When there is a runtime error during the development phase of your Next.js application, you will encounter an overlay. It is a modal that covers the webpage. It is only visible when the development server runs using next dev
, npm run dev
, or yarn dev
and not in production. Fixing the error will automatically dismiss the overlay.
Here is an example of an overlay:
Handling Server Errors
Next.js provides a static 500 page by default to handle server-side errors that occur in your application. You can also customize this page by creating a pages/500.js
file.
Having a 500 page in your application does not show specific errors to the app user.
You can also use 404 page to handle specific runtime error like file not found
.
Handling Client Errors
React Error Boundaries is a graceful way to handle a JavaScript error on the client so that the other parts of the application continue working. In addition to preventing the page from crashing, it allows you to provide a custom fallback component and even log error information.
To use Error Boundaries for your Next.js application, you must create a class component ErrorBoundary
and wrap the Component
prop in the pages/_app.js
file. This component will be responsible to:
- Render a fallback UI after an error is thrown
- Provide a way to reset the Application’s state
- Log error information
You can create an ErrorBoundary
class component by extending React.Component
. For example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
// Define a state variable to track whether is an error or not
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI
return { hasError: true }
}
componentDidCatch(error, errorInfo) {
// You can use your own error logging service here
console.log({ error, errorInfo })
}
render() {
// Check if the error is thrown
if (this.state.hasError) {
// You can render any custom fallback UI
return (
<div>
<h2>Oops, there is an error!</h2>
<button
type="button"
onClick={() => this.setState({ hasError: false })}
>
Try again?
</button>
</div>
)
}
// Return children components in case of no error
return this.props.children
}
}
export default ErrorBoundary
The ErrorBoundary
component keeps track of an hasError
state. The value of this state variable is a boolean. When the value of hasError
is true
, then the ErrorBoundary
component will render a fallback UI. Otherwise, it will render the children components.
After creating an ErrorBoundary
component, import it in the pages/_app.js
file to wrap the Component
prop in your Next.js application.
// Import the ErrorBoundary component
import ErrorBoundary from '../components/ErrorBoundary'
function MyApp({ Component, pageProps }) {
return (
// Wrap the Component prop with ErrorBoundary component
<ErrorBoundary>
<Component {...pageProps} />
</ErrorBoundary>
)
}
export default MyApp
You can learn more about Error Boundaries in React’s documentation.
Reporting Errors
To monitor client errors, use a service like Sentry, Bugsnag or Datadog.
description |
---|
Override and extend the built-in Error page to handle custom errors. |
404 Page
A 404 page may be accessed very often. Server-rendering an error page for every visit increases the load of the Next.js server. This can result in increased costs and slow experiences.
To avoid the above pitfalls, Next.js provides a static 404 page by default without having to add any additional files.
Customizing The 404 Page
To create a custom 404 page you can create a pages/404.js
file. This file is statically generated at build time.
// pages/404.js export default function Custom404() { return <h1>404 - Page Not Found</h1> }
Note: You can use
getStaticProps
inside this page if you need to fetch data at build time.
500 Page
Server-rendering an error page for every visit adds complexity to responding to errors. To help users get responses to errors as fast as possible, Next.js provides a static 500 page by default without having to add any additional files.
Customizing The 500 Page
To customize the 500 page you can create a pages/500.js
file. This file is statically generated at build time.
// pages/500.js export default function Custom500() { return <h1>500 - Server-side error occurred</h1> }
Note: You can use
getStaticProps
inside this page if you need to fetch data at build time.
More Advanced Error Page Customizing
500 errors are handled both client-side and server-side by the Error
component. If you wish to override it, define the file pages/_error.js
and add the following code:
function Error({ statusCode }) { return ( <p> {statusCode ? `An error ${statusCode} occurred on server` : 'An error occurred on client'} </p> ) } Error.getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 404 return { statusCode } } export default Error
pages/_error.js
is only used in production. In development you’ll get an error with the call stack to know where the error originated from.
Reusing the built-in error page
If you want to render the built-in error page you can by importing the Error
component:
import Error from 'next/error' export async function getServerSideProps() { const res = await fetch('https://api.github.com/repos/vercel/next.js') const errorCode = res.ok ? false : res.status const json = await res.json() return { props: { errorCode, stars: json.stargazers_count }, } } export default function Page({ errorCode, stars }) { if (errorCode) { return <Error statusCode={errorCode} /> } return <div>Next stars: {stars}</div> }
The Error
component also takes title
as a property if you want to pass in a text message along with a statusCode
.
If you have a custom Error
component be sure to import that one instead. next/error
exports the default component used by Next.js.
Caveats
Error
does not currently support Next.js Data Fetching methods likegetStaticProps
orgetServerSideProps
._error
, like_app
, is a reserved pathname._error
is used to define the customized layouts and behaviors of the error pages./_error
will render 404 when accessed directly via routing or rendering in a custom server.
Currently I am following this example on how to redirect users in getInitialProps
https://github.com/zeit/next.js/wiki/Redirecting-in-%60getInitialProps%60
The problem is, if I want to return 404 like this, it will return a blank page instead of the usual Next.js 404 error page.
context.res.writeHead(404)
context.res.end();
Please note I know using ExpressJs and using statuscode 404 works, however, for this project I am not allowed to use ExpressJs so I need to use typical nodejs writeHead to do it.
asked Dec 1, 2017 at 4:08
1
Next v10 allows to return 404 page (not with props, but just plain as it is below)
if (!checkItem) {
return {
notFound: true
}
}
Full code that works for me: ✅✅✅
export const getServerSideProps = wrapper.getServerSideProps(async ({ req, res, locale, query, store }) => {
const { productId, categoryId } = query
const checkItem = await getProductBySlugSSR(productId, categoryId, store)
if (!checkItem) {
return { // <-----------------does the trick here!!
notFound: true
}
}
return {
props: {
...await serverSideTranslations(locale, ['common']),
}
}
})
Documentation: https://nextjs.org/blog/next-10#notfound-support
Vadorequest
15.7k24 gold badges112 silver badges208 bronze badges
answered Apr 28, 2021 at 12:04
5
In order to do that, you’ll have to render the Error page in your page.
You can do something like this:
import React from 'react'
import ErrorPage from 'next/error'
class HomePage extends React.Component {
static async getInitialProps(context) {
try {
const data = await retrieveSomeData()
return { data }
} catch (err) {
// Assuming that `err` has a `status` property with the HTTP status code.
if (context.res) {
context.res.writeHead(err.status)
}
return { err: { statusCode: err.status } }
}
}
render() {
const { err, data } = this.props
if (err) {
return <ErrorPage statusCode={err.statusCode} />
}
/*
* return <Something data={data} />
*/
}
}
If you have a custom error page, instead of importing next/error
, you’ll have to import your custom _error
page.
answered Dec 14, 2017 at 17:34
Bertrand MarronBertrand Marron
21.1k8 gold badges58 silver badges94 bronze badges
0
Implement your getInitialProps along the lines of:
static async getInitialProps(context) {
const {res} = context;
...
if ([something went wrong]) {
if (res) {
res.statusCode = 404;
}
return {
err: {
statusCode: 404
},
};
}
...
Then in render() check if err
is defined in state, in which case return the ErrorPage (default or custom one, depending on your implementation) and that’s it! The statusCode inside err is just for more granular message on the ErrorPage so it needs to be passed for it as props.
answered Jan 16, 2019 at 9:20
import App, { Container } from 'next/app'
import React from 'react'
import Head from 'next/head'
import * as Sentry from '@sentry/node'
import Error from './_error'
require('es6-promise').polyfill()
require('isomorphic-fetch')
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {}
let e
if (Component.getInitialProps) {
try {
pageProps = await Component.getInitialProps(ctx)
} catch (error) {
e = error
Sentry.captureException(error) //report to sentry
}
}
return { pageProps, e }
}
render() {
const { Component, pageProps, e } = this.props
if (e) {
return <Error /> // customize your error page
}
return (
<Container>
<Head>
<title> Your title</title>
</Head>
<Component {...pageProps} />
</Container>
)
}
}
export default MyApp
This works like a charm ~
just try catch in next/app, then it works for all the pages
answered Jan 25, 2019 at 7:01
Shawn WangShawn Wang
2,1241 gold badge16 silver badges18 bronze badges
If you just have to implement the 404 PAGE like you do in cra
the code provided can be helpful:
eg.
import AComponent from '../acomponent';
import Error from '../error';
const User = (data) => {
return data.id ? <AComponent /> : <Error />
}
User.getInitialProps = async (ctx) => {
const res = await fetch(...data) // list of items = []
const data = await res.json()
return data;
}
answered Oct 1, 2020 at 7:47
VinceVince
77611 silver badges20 bronze badges
Here’s how I do it
import ErrorPage from 'next/error'
const Mycomponenet = () =>{
if (!exists) {
return <ErrorPage statusCode={404}/>
}
}
answered Dec 12, 2022 at 16:27
tsukyonomi06tsukyonomi06
4141 gold badge5 silver badges15 bronze badges
I am using this and it works for me
res.sendStatus(404)
answered Jan 26, 2022 at 10:17
Fahad AliFahad Ali
371 silver badge7 bronze badges
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 { Typography, Button } from
'@mui/material'
import Link from
'next/link'
import React from
'react'
const PageNotFound = () => {
return
(
<>
<Typography variant=
'h5'
>
Sorry,
this
page is not
found
in
GeeksForGeeks !!!
</Typography>
{
}
<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 { Box, Chip, Stack, Typography } from
"@mui/material"
;
import Head from
"next/head"
;
import Image from
"next/image"
;
import Link from
"next/link"
;
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 { Component } from
"react"
;
export
default
class About extends Component {
static async getInitialProps() {
const statusCode = res.status > 200 ? res.status :
false
;
const data = await res.json();
return
{ user: data, statusCode };
}
render() {
const { user, statusCode } =
this
.props;
if
(statusCode) {
return
<Error statusCode={statusCode} />;
}
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 Layout from
"../components/Layout"
;
export
default
({ statusCode }) => (
<Layout title=
"Error!!!"
>
{
}
{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.
There is always that moment a user ends up on a page that doesn’t exist.
So let’s see how we can make these pages stand out more by adding our pages for each error page.
Creating a 404 page in Next.js
Let’s start with the most common one, the 404 page. This one often occurs if the users end up on a page that no longer exists or make a typo in the URL.
Let’s try to find a random page called /does-not-exist
and see what happens:
So we get the above error because we said fallback is true for the getStaticPaths
function.
That means it should always try to resolve the page even if it can’t find the static props.
To fix this, we can set the fallback to false like this, which will redirect to a 404 if it can’t resolve.
export async function getStaticPaths() {
const pagesWithSlugs = await getAllPagesWithSlugs();
return {
paths: pagesWithSlugs.edges.map(({node}) => `/${node.slug}`) || [],
fallback: false,
};
}
To create the 404 page, we can create a page called 404.js
in our pages
directory.
export default function Custom404() {
return (
<div className="flex items-center justify-center h-screen mx-2 my-2 overflow-hidden ">
<div className="px-6 py-4 rounded shadow-lg">
<div className="mb-2 text-xl font-bold">
404 - Sorry could not find this page 😅
</div>
</div>
</div>
);
}
And now, when reloading the page, we should see the following page.
500 error page in Next.js
Sometimes there might be something else wrong, and our website might throw a 500 error.
We can create a custom error page for those pages as well.
Create a file called 500.js
in your pages
directory.
export default function Custom500() {
return (
<div className="flex items-center justify-center h-screen mx-2 my-2 overflow-hidden ">
<div className="px-6 py-4 rounded shadow-lg">
<div className="mb-2 text-xl font-bold">500 - Server error 😭</div>
</div>
</div>
);
}
This is the basic approach to having custom error pages in Next.js.
As always, you can find the complete code on GitHub.
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
After a lot of misunderstandings and frustration with the documentation on the Next.js docs I decided it might be worth explaining how to properly return a 404 error in getServerSideProps with Next.js.
What’s the problem with Next.js and its error pages?
If you’re reading this you’re probably aware that Next.js has a fairly clear page about showing custom error pages.
I suppose most people will be absolutely fine with the solutions provided in the documentation. However, if you’re anything like me and do a lot of SEO work, it’s likely that after a couple of months you’ll start noticing Google indexing pages that don’t actually exist.
For the longest time I didn’t understand why this was happening. I’d visit a non-existing page and Next.js would spit out a 404 error, but despite this (and a lot of wasted time on Google Search Console), those pages would be recognised as valid.
Why your Next.js error pages are not actual error pages
The solution to the problem, as it usually is more often than not, was very simple. While Next.js renders an error page, it doesn’t actually respond with an error. Weird, I know.
This means that while you can be viewing a 404 error, the page is actually responding with a 200
code. To search engines, this essentially translates to: «Everything went fine and we found the page». Rather than actually responding with a 404
, which tells search engines that page doesn’t exist.
In retrospect this actually makes sense, as it’s impossible to change the response code from a component. Unfortunately this prospect didn’t even cross my mind for the longest time.
How to respond with a 404 error in Next.js
Returning a 404 error in Next.js’ getServerSideProps is actually really simple. In your getServerSideProps, where you’re fetching the data for your page, you’ll just need to add a couple of lines of code:
export async function getServerSideProps({ res }) {
const data = await fetch("https://api.github.com/repos/vercel/next.js");
const errorCode = data.ok ? false : data.statusCode;
if (errorCode) {
res.statusCode = errorCode;
}
const json = await data.json();
return {
props: { errorCode, stars: json.stargazers_count }
};
}
The main difference between the code snippet we have above and the one in the docs is that we manually set the response with res.statusCode = errorCode;
.
Here we’re simplifying the code a lot by expecting our server to also throw us the relevant error. (But if your API isn’t set up to handle that you can simply set it manually like so: res.statusCode = 404
.)
Then, in our component we can simply check if our errorCode
prop exists and display our component before rendering anything else.
export default function Page({ errorCode, stars }) {
if (errorCode) {
return <Error statusCode={errorCode} />;
}
}
That’s all!
At Ironeko we’re big fans of Next.js, if you’re one too make sure to check out our running Next.js in Capacitor on Android and running Next.js in Capacitor on iOS guides!