not-found.js in Next.js

not-found.js is a special file in Next.js that lets you show a custom UI when a route or requested data does not exist. It replaces the default 404 page with your own design.

Basic Idea

When Next.js cannot find a page or resource, it automatically renders the nearest not-found.js.

app/not-found.js

This file acts as a custom 404 handler.

Example

export default function NotFound() {
  return (
    <div>
      <h1>404 — Page Not Found</h1>
      <p>The page you are looking for does not exist.</p>
    </div>
  );
}

Whenever an invalid route is accessed, this UI appears.

Triggering Not Found Programmatically

You can manually show the not-found page when data is missing.

import { notFound } from "next/navigation";

export default async function Page() {
  const data = null;

  if (!data) {
    notFound();
  }

  return <div>Data loaded</div>;
}

This is useful when a database record or API response doesn’t exist.

Real World Example

Imagine clicking a product link that no longer exists. Instead of a broken screen, users see a helpful message guiding them back.

Why not-found.js Matters

Interview Tip

not-found.js allows developers to create custom 404 experiences and can be triggered automatically or programmatically using thenotFound() function.