What is error.js in Next.js: Purpose and Usage Explained
_error.js in Next.js is a special file used to customize the error page shown when your app encounters an error like a 404 or server error. It lets you create friendly, styled error messages instead of the default plain ones.How It Works
Think of _error.js as the safety net for your Next.js app. When something goes wrong—like a user visits a page that doesn't exist (404) or the server has a problem (500)—Next.js shows an error page. By default, this page is simple and generic.
Creating an _error.js file lets you catch these errors and show a nicer, custom page. It’s like having a friendly receptionist who guides visitors when they get lost instead of just saying "Page not found" coldly.
This file exports a React component that Next.js uses automatically for error pages. You can add your own messages, styles, and even buttons to help users navigate back to safety.
Example
This example shows a simple _error.js file that displays a custom message and the error status code.
import React from 'react'; function Error({ statusCode }) { return ( <div style={{ textAlign: 'center', marginTop: '50px' }}> <h1>{statusCode ? `Error ${statusCode}` : 'An error occurred'}</h1> <p>Sorry, something went wrong. Please try again later.</p> </div> ); } Error.getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 404; return { statusCode }; }; export default Error;
When to Use
Use _error.js when you want to improve user experience by showing custom error pages instead of the default Next.js error screen. This is especially helpful for branding and guiding users back to working parts of your site.
Common real-world uses include:
- Custom 404 pages that suggest navigation options or search
- Friendly messages for server errors (500) explaining the issue
- Logging or tracking errors by adding analytics inside the error component
Key Points
- _error.js customizes error pages in Next.js apps.
- It handles HTTP errors like 404 (not found) and 500 (server error).
- You export a React component that Next.js uses automatically.
- Use it to improve user experience and branding on error pages.
- Supports fetching error status codes via
getInitialProps.
Key Takeaways
_error.js lets you create custom error pages in Next.js.