Next.js: 404 error page and 404 error code

Last updated on January 14, 2021 A Goodman Loading... Post a comment

In this article, we will take a look at how to handle the 404 error in Next.js

Discussion

The 404 error tells us that the browser was able to communicate with our web server but the server could not find what was requested. This usually happens when a user enters a wrong URL, when something that once existed but has been removed, or a URL has been changed but has not been redirected correctly.

Next.js offers a default 404 error page out of the box. This one is completely static and generated at build time. It displays nothing but some plain text of “404 | This page could not be found”.

In the old days, the default 404 error page wasn’t a real 404 page. It used to come with a 200 status code. That doesn’t make much sense. Thankfully, things change, and the new versions of Next.js respond 404 status code as expected. You can check it out by using Chrome developer tools, like this (I am using Next.js 10.05):

404 status code

Make A Custom 404 Page

Generally, the 404 page is hit very often. As mentioned above, this page is static so it can help you reduce the load of your server. However, we can do something better like adding a link to the homepage or a search box. To achieve so, we need to make a custom 404 error page.

1. Create a new file named 404.js in your pages folder.

2. Add things you want to display to the user when he or she meets the 404 page. For example:

import Link from 'next/link';

const MyCustom404Page = (props) => {
  return (
    <div
      style={{
        marginTop: 100,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <h1>404</h1>
      <h2>
        <Link href="/">
          <a style={{ color: 'blue', textDecoration: 'underline' }}>
            Go To Home Page
          </a>
        </Link>
      </h2>
      <p>Sorry, the content you are looking for cuould not be found.</p>
    </div>
  );
};

export default MyCustom404Page;

Output:

Show Dynamic Content on 404 Page

There are times when you want to show some dynamic content on your 404 page like the latest news, the recommended products, etc. In these cases, we can use the getStaticProps method. This approach will help you save server resources much more than using getServerSideProps.

In the example below, the content of the 404 page is not only generated at build time but also is generated once every 60 seconds or when a request comes in.

import Link from 'next/link';

const MyCustom404Page = (props) => {
  return (
    <div
      style={{
        marginTop: 100,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <h1>404 - Page Not Found</h1>
      <h2>
        <Link href="/">
          <a style={{ color: 'blue', textDecoration: 'underline' }}>
            Go To Home Page
          </a>
        </Link>
      </h2>
      <p>Or check out our latest news:</p>
      <hr />
      <ul>
        {posts.map((articles) => (
          <li>{/* article title and href here */}</li>
        ))}
      </ul>
    </div>
  );
};

export async function getStaticProps() {
  // Call an external API endpoint to get posts.
  const res = await fetch('YOUR_API_URL');
  const posts = await res.json();

  return {
    props: {
      posts,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every second
    revalidate: 60,
  };
}

export default MyCustom404Page;

You can find more information here.

Conclusion

In this article, we’ve covered a lot of things about the 404 error in Next.js. This can help us to optimize and improve our projects in the future.

If you would like to learn more about Next.js, take a look at the following articles: How to use Ant Design in a Next.js projectHow to use Font Awesome 5 with Next.jsHow to add Favicon to a Next.js app, or check out our Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles