0
0
NextjsConceptBeginner · 3 min read

What is not-found.js in Next.js: Explanation and Usage

not-found.js in Next.js is a special file that renders a custom 404 page when a requested page is not found. It helps you show friendly messages or designs instead of a default error. This file is placed in the app directory and automatically triggers when Next.js cannot find the requested route.
⚙️

How It Works

Imagine you visit a store and ask for a product that is not on the shelves. Instead of leaving you confused, the store clerk politely tells you the item is not available. In Next.js, not-found.js acts like that helpful clerk. When a user tries to visit a page that does not exist, Next.js looks for this file to show a custom message or page.

This file lives inside the app folder and is automatically used by Next.js when no matching page is found. It replaces the default browser 404 error with your own friendly design or message. This makes your website feel more polished and user-friendly.

đź’»

Example

This example shows a simple not-found.js file that displays a custom message when a page is missing.

javascript
export default function NotFound() {
  return (
    <main style={{ padding: '2rem', textAlign: 'center' }}>
      <h1>Oops! Page Not Found</h1>
      <p>Sorry, we couldn't find the page you were looking for.</p>
    </main>
  )
}
Output
A centered page with the heading 'Oops! Page Not Found' and a message 'Sorry, we couldn't find the page you were looking for.'
🎯

When to Use

Use not-found.js whenever you want to improve user experience by showing a friendly message for missing pages. It is especially useful for websites with many pages or dynamic routes where users might mistype URLs or follow broken links.

For example, an online store can use it to guide customers back to the homepage or suggest popular products instead of showing a plain error. It also helps keep your site consistent in style and branding.

âś…

Key Points

  • Automatic: Next.js uses not-found.js automatically for missing pages.
  • Customizable: You control the look and message to fit your site style.
  • Placed in app folder: It must be inside the app directory.
  • Improves UX: Helps users understand and recover from navigation errors.
âś…

Key Takeaways

not-found.js creates a custom 404 page in Next.js for missing routes.
It lives inside the app directory and triggers automatically.
Use it to show friendly messages and keep your site user-friendly.
Customizing this page improves your website’s professionalism and navigation.
It is simple to create and requires only a React component export.