Morteza.online

Custom 404 Pages in Next.js 15: Handle Errors with Style

by Morteza on 1/28/2025

A 404 page doesn’t have to be boring! In Next.js 15, handling "not found" errors is easier than ever with the "notFound" function and custom "not-found.js". Let’s turn dead ends into delightful moments with a creative, user-friendly 404 page, complete with ASCII art and a touch of personality.

Handling 404s with Next.js 15

Next.js 15 introduces a simple and effective way to handle "not found" pages. By using the notFound function from next/navigation, you can trigger a 404 response and customize the user experience. Let’s walk through an example.

Catch-All Not Found Page

Here’s how you can create a catch-all route to handle 404s:

// app/[...notfound]/page.js
import { notFound } from "next/navigation";

export default function NotFoundCatchAll() {
  notFound();
}

This dynamic route ensures that any unmatched URL will call the notFound function, redirecting users to your custom 404 page.

Designing the Custom 404 Page

Now, let’s add some personality to the 404 page. Here’s an example with ASCII art:

// app/not-found.js
import Link from "next/link";

import styles from "./page.module.css";

export default function NotFound() {
  return (
    <div>
      <pre className={styles.notFoundPre}>{`
    44       00000         44   
   444      00   00       444   
 44  4      00   00     44  4   
44444444    00   00    44444444 
   444       00000        444   
                                
      `}</pre>
      <p>The page you're looking for has gone on a coffee break. Please try again later, or check your URL for typos. May the source be with you!</p>
      <div>
        <Link href="/">or visit home page</Link>
      </div>
    </div>
  );
}

Demo

Live example in my personal website: https://morteza.online/not-available-page 404.png

What’s Happening Here?

  1. ASCII Art Fun: The pre tag displays ASCII art to add a bit of humor to your 404 page.
  2. Helpful Message: A friendly note explains what happened and how to proceed.
  3. Navigation Link: A link back to the homepage provides an easy way to recover.

Why a Good 404 Page Matters

  • Improved UX: A creative 404 page can reduce frustration and make your site more memorable.
  • SEO Benefits: A custom 404 page keeps users engaged and reduces bounce rates.
  • Brand Personality: It’s an opportunity to showcase your brand’s unique style.

Final Thoughts

With Next.js 15, creating custom 404 pages is both easy and fun. By combining functionality with creativity, you can turn errors into opportunities to engage and delight your users. Don’t forget, a little ASCII art goes a long way!

Ready to upgrade your 404 pages? Dive into Next.js 15 and start building something amazing today!