Creating a custom error page in NextJS

Sometimes errors occur on the pages and we want to handle that and show a better experience for the user.

cover for Creating a custom error page in NextJS


Usually, an error page is a not complex one, just with some orientations to help the user to know what is happening and how to deal with that. Next.js already comes with a static default 404 page, decreasing the usage of the Next.js server on each 404 requests:

Creating your custom 404 page is very simple, you will need to create a file in the pages directory: pages/404.js and you can create the page as usual, you would do for other pages. This page will be generated statically but you can still fetch data using the getStaticProps function at build time.

Below it’s the code of the Roadevmap 404 page:

export default function NotFound({ resultSize }) {
  return (
    <Fragment>
      <Head>
        <title>404 - There is nothing at this URL</title>
        <meta name="description" content="Oops... There is nothing at this URL. The page you were looking for does not exist!" />
       </Head>
       
       <NotFoundContainer>
         <PrimaryHeading>
           Oops. The page you were looking for does not exist!
         </PrimaryHeading>

         <Image src="/assets/svgs/undraw/Empty.svg" height={300} width={300} alt="page not found" />
         <h2>
           What's the next step? maybe you could <Link href="/"> go to the homepage</Link> or take a look at <b> our last posts.</b>                  </h2>
      <ArticlesCategoriesSuggestion />
    </NotFoundContainer>
  </Fragment>
);
}

Below it’s a screenshot of the Roadevmap 404 page:

Roadevmap's custom error page


Conclusion

Creating custom error pages is a great layout enhancement, it helps the user and also can make the user continues navigating on the page.