In any application, the error page is thrown if any error occurs in the client or server.

404 error is a type of error if the requested resources path page is not able found on the server.

It is an easy and quick way of creating custom 404 pages in Next.js.

Consider, the user request `localhost:3000/XYZ, where XYZ route path is not found, Then It gives a Default 404 page as shown below.

NextJS Custom 404 error page example

This page is an inbuilt 404 static page provided by the Next.js framework.

How to create a custom 404 error page in Next.js

you can create a 404 page easy way.

Following are the steps to create a custom error page

  • Create a react component with the name 404.tsx in the pages folder
  • Add the custom code to how you want to display the 404.TSX page.
import styles from './404.module.css'

export default function FourNotFourPage() {
  return <div className={styles.heading}>
    <h1>404 Error Page</h1>
    <h3>Requested page not found</h3>
  </div>
}
  • You can still add CSS styles with global or component CSS modules.
  • You can add logos, custom messages, and links to it.
  • You can also write data retrieving code in getStaticProps if you need to fetch data on the 404 page.

404 page is generated at build time during the next build or next start phase.

How to show 404 page for dynamic routes path not found in NextJS page.

Sometimes, you have a dynamic route and you want to throw a 404 error if any dynamic route name or id is not found.

For example, localhost:3000/post/[name] where is the name of the post.

In the React component, you need to validate the name parameter and check if not found, you need to redirect to the 404 page.

First, Import the router and get the name parameter from the router. query. if the name is empty or not found, push to router object to redirect to the 404 page.

You can also write a data fetching logic in getStaticProps and do the name validation.

pages/post/[name].tsx:

import { useRouter } from 'next/router'

const PostPage = () => {
  const router = useRouter()
  const { name } = router.query
   if(!name){
       router.push('/404')
   }
  return <h1>Post: {name}</h1>
}

export default PostPage
`