Error Handling

Errors will inevitably happen. A database might go offline, or an API might return malformed JSON. Next.js provides robust error handling out of the box to prevent your entire application from crashing and turning white.

App Router Error Boundaries (`error.js`)

In the modern App router, you can create an error.js file anywhere inside the app/ directory. When a Server Component or Client Component crashes within that particular route segment, the error.js component catches it and renders gracefully. The rest of your layout (like your Navbar and Sidebar) remains fully rendered and functional!

'use client'; // Error components must be Client Components
import { useEffect } from 'react';

export default function ErrorBoundary({ error, reset }) {
  useEffect(() => {
    // Log the error to an error reporting service like Sentry
    console.error(error);
  }, [error]);

  return (
    <div className="error-container">
      <h2>Something went wrong!</h2>
      <p>{error.message}</p>
      {/* Allows the user to try rendering the segment again */}
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Custom 404 Pages (`not-found.js` or `404.js`)

When a user visits a route that does not exist, Next.js displays a generic "404 - This page could not be found" screen. You can fully customize this easily.

  • App Router: Create a file named not-found.js inside your app/ directory.
  • Pages Router: Create a file named 404.js inside your pages/ directory.
// app/not-found.js
import Link from 'next/link';

export default function NotFound() {
  return (
    <div style={{ textAlign: 'center', marginTop: '100px' }}>
      <h1>404 - Look around you, you're lost.</h1>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  );
}

Custom 500 Pages (`500.js`)

If you are using the older Pages Router and a server-side crash occurs (like inside `getServerSideProps`), Next.js natively supports custom 500 pages. Simply create a pages/500.js file.

Global Errors (`global-error.js`)

In the App router, what happens if your root layout.js crashes? Because error.js is nested *inside* the layout, it cannot catch root layout errors! For these devastating, top-level crashes, you can define a global-error.js file. This file replaces the entire HTML document.

Conclusion

By implementing custom error boundaries and 404 pages, you maintain a highly professional user experience even during partial outages. Next up, we handle User Authentication.