How to Create a Custom 404 Page in Next.js Easily
In Next.js, create a
404.js file inside the pages folder to define a custom 404 error page. This page automatically shows when users visit a non-existent route, improving user experience with a friendly message or navigation options.Syntax
To create a custom 404 page in Next.js, add a file named 404.js inside the pages directory. This file should export a React component that renders the content you want users to see when they hit a missing page.
Next.js automatically detects this file and uses it for all 404 errors.
javascript
export default function Custom404() { return ( <main style={{ padding: '2rem', textAlign: 'center' }}> <h1>404 - Page Not Found</h1> <p>Sorry, the page you are looking for does not exist.</p> </main> ) }
Output
A simple page with a heading '404 - Page Not Found' and a message below it centered on the screen.
Example
This example shows a complete custom 404 page with a heading, message, and a link back to the homepage. It uses simple inline styles for layout and Next.js Link component for navigation.
javascript
import Link from 'next/link' export default function Custom404() { return ( <main style={{ padding: '3rem', textAlign: 'center' }}> <h1 style={{ fontSize: '3rem', marginBottom: '1rem' }}>404 - Page Not Found</h1> <p style={{ fontSize: '1.25rem', marginBottom: '2rem' }}> Oops! We can't find the page you're looking for. </p> <Link href="/"> <a style={{ color: '#0070f3', textDecoration: 'underline' }} aria-label="Go back to homepage"> Go back home </a> </Link> </main> ) }
Output
A centered page with a large '404 - Page Not Found' heading, a friendly message, and a clickable link labeled 'Go back home' that navigates to the homepage.
Common Pitfalls
- Not naming the file exactly
404.jsinside thepagesfolder will prevent Next.js from recognizing it as the 404 page. - Using class components or older React patterns is discouraged; use functional components instead.
- For static export (
next export), the 404 page must be present to handle missing routes. - For dynamic routes, ensure fallback handling does not conflict with the 404 page.
javascript
/* Wrong: Naming file as NotFound.js will NOT work */ export default function NotFound() { return <h1>Page Not Found</h1> } /* Right: File named 404.js with this content */ export default function Custom404() { return <h1>Page Not Found</h1> }
Quick Reference
How to create a 404 page in Next.js:
- Create
pages/404.js - Export a React functional component
- Design your custom message and navigation
- Next.js uses this page automatically for 404 errors
Key Takeaways
Create a file named 404.js inside the pages folder to define a custom 404 page.
Use a React functional component to render your custom message and navigation.
Next.js automatically shows this page for all non-existent routes.
Ensure the file is named exactly 404.js to work correctly.
Use Next.js Link component for accessible navigation back to valid pages.