Loading...

Section

Handling 404 Not Found Pages

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

In any web application, users will inevitably encounter situations where a requested page doesn't exist. This is where the 404 Not Found error comes into play. Next.js provides a straightforward and elegant way to handle these scenarios, ensuring a better user experience by displaying a custom, informative page instead of a generic browser error.

Next.js automatically handles 404 errors for routes that don't match any of your defined pages. By default, you'll see a basic '404 - Not Found' page. However, to provide a more branded and helpful experience, you can create your own custom 404 page.

To implement a custom 404 page, you simply need to create a file named 404.js (or 404.tsx for TypeScript) within your pages directory. Next.js will automatically recognize and serve this file whenever a requested route does not match any other page in your application.

import Link from 'next/link';

export default function Custom404() {
  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1>404 - Page Not Found</h1>
      <p>Oops! The page you are looking for does not exist.</p>
      <Link href="/">
        <a>Go back to the homepage</a>
      </Link>
    </div>
  );
}

In the example above, we've created a simple Custom404 component. It displays a friendly message and includes a link back to the homepage using Next.js's Link component for client-side navigation. This is a crucial step in guiding lost users back to relevant parts of your application.

When a user navigates to a non-existent URL, Next.js performs the following steps:

  1. It checks its routing table for a matching page component.
  2. If no match is found, it looks for a pages/404.js file.
  3. If pages/404.js exists, it renders that component.
  4. If pages/404.js does not exist, it renders the default Next.js 404 page.
graph TD;
    A[User requests a URL] --> B{Is URL mapped to a page?};
    B -- No --> C{Does 'pages/404.js' exist?};
    B -- Yes --> D[Render the matching page];
    C -- Yes --> E[Render 'pages/404.js'];
    C -- No --> F[Render default Next.js 404 page];

It's good practice to make your 404 page consistent with the rest of your application's design and to provide helpful links or search functionality to assist users in finding what they were looking for. This small effort can significantly improve user satisfaction and reduce bounce rates.