Last updated on May 22, 2021 by Suraj Sharma
In this tutorial, you’ll learn how you can create a custom 404 (page not found) error page in Nextjs and Typescript.
Next.js provides a default 404
error page, which looks like this
However, Next.js provides us the flexibility to create our own error page.
Let’s start creating a custom error page
First, create a file called 404.ts
inside the /pages
folder
Then, define a <Custom404Page />
component inside the file and return the DOM elements you want to have for your custom page.
For Example,
// 404.tsx
import React from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Head from 'next/head';
import { NextPage } from 'next';
const useStyles = makeStyles({
root: {
display: 'flex',
flexDirection: 'column',
minHeight: 540,
justifyContent: 'center',
alignItems: 'center',
alignContent: 'center'
},
mt: {
marginTop: 10
}
})
const Custom404Page:NextPage = () => {
const classes = useStyles();
return (
<>
<Head>
<title>The page you were looking for doesn't exist | 404</title>
</Head>
<Box className={classes.root}>
<img src="/favicons/custom-404.jpeg" width="320" height="320" />
<Typography className={classes.mt}>
This page does not exist
</Typography>
<Typography className={classes.mt}>
<a href="/">Return to Home Page</a>
</Typography>
</Box>
</>
)
}
export default Custom404Page;
The above code is taken from the custom 404 error page on my website, Demo
Now, run the dev server
npm run dev
Try to hit an incorrect route
You will see the custom 404 page instead of the Next.js default 404 page
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.