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.
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> ) }
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.jsautomatically for missing pages. - Customizable: You control the look and message to fit your site style.
- Placed in app folder: It must be inside the
appdirectory. - 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.app directory and triggers automatically.