In this section, we will explore how to create custom error pages in Next.js. Custom error pages enhance user experience by providing more informative and visually appealing error messages instead of the default error page. We'll cover various types of errors, including server-side and client-side errors, and show you how to handle them effectively.
Next.js provides built-in support for custom error pages, which allows developers to create a consistent look and feel across their application. Custom error pages can be particularly useful for handling 404 (Not Found) errors, 500 (Internal Server Error), and other client-side errors.
Next.js automatically looks for specific files in the pages directory to render custom error pages. Let's start by creating these files.
To handle 404 errors, create a file named _error.js or _error.tsx (depending on your project setup) in the pages directory. This file will render whenever a page is not found.
// pages/_error.js
import React from 'react';
const Custom404 = ({ statusCode }) => {
return (
<div style={{ textAlign: 'center', padding: '50px' }}>
<h1>{statusCode === 404 ? '404 - Page Not Found' : `An error ${statusCode} occurred`}</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</div>
);
};
export default Custom404;
For server-side errors, Next.js also uses the _error.js or _error.tsx file. However, if you want to handle specific server-side errors differently, you can create additional logic within this file.
// pages/_error.js (continued)
import React from 'react';
const Custom500 = ({ statusCode }) => {
return (
<div style={{ textAlign: 'center', padding: '50px' }}>
<h1>{statusCode === 404 ? '404 - Page Not Found' : `An error ${statusCode} occurred`}</h1>
{statusCode === 500 && (
<p>Sorry, something went wrong on our end. Please try again later.</p>
)}
</div>
);
};
export default Custom500;
Client-side errors can occur due to JavaScript runtime issues or API failures. Next.js provides a way to handle these errors using the ErrorBoundary component.
Create a reusable ErrorBoundary component that will catch and display custom error messages.
// components/ErrorBoundary.js
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can log the error information to an error reporting service
console.error('ErrorBoundary caught an error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Wrap your components with the ErrorBoundary to handle client-side errors.
// pages/index.js
import React from 'react';
import ErrorBoundary from '../components/ErrorBoundary';
const HomePage = () => {
return (
<div>
<h1>Welcome to Next.js!</h1>
{/* Your component logic here */}
</div>
);
};
export default function Home() {
return (
<ErrorBoundary>
<HomePage />
</ErrorBoundary>
);
}
Custom error pages in Next.js are essential for improving the user experience by providing meaningful feedback when something goes wrong. By following the steps outlined in this tutorial, you can create robust and visually appealing error pages that enhance the overall quality of your application.
Remember to test your custom error pages thoroughly to ensure they work as expected across different scenarios and devices.