Error handling is a critical aspect of building robust and user-friendly web applications. In Next.js, you can handle errors gracefully and create custom error pages to improve the user experience. Whether it’s a 404 page for missing routes or a 500 page for server errors, Next.js provides built-in support for error handling. In this article, we’ll explore how to handle errors and create custom error pages in Next.js.
1. Built-in Error Pages
Next.js comes with built-in error pages for common HTTP errors, such as 404 (Not Found) and 500 (Internal Server Error). These pages are automatically displayed when an error occurs, but you can customize them to match your application’s design.
404 Page
The 404 page is displayed when a user tries to access a route that doesn’t exist. To create a custom 404 page, add a file named 404.js
in the pages
directory.
// pages/404.js
export default function Custom404() {
return <h1>404 - Page Not Found</h1>;
}
500 Page
The 500 page is displayed when an unexpected error occurs on the server. To create a custom 500 page, add a file named 500.js
in the pages
directory.
// pages/500.js
export default function Custom500() {
return <h1>500 - Server Error</h1>;
}
2. Handling Errors in API Routes
Next.js API routes allow you to handle backend logic, such as fetching data from a database or processing form submissions. When an error occurs in an API route, you can return an appropriate status code and error message.
// pages/api/data.js
export default function handler(req, res) {
try {
// Simulate an error
throw new Error('Something went wrong');
} catch (error) {
res.status(500).json({ message: error.message });
}
}
3. Custom Error Handling in Pages
You can handle errors in your pages using the getServerSideProps
or getStaticProps
functions. If an error occurs, you can redirect the user to an error page or display an error message.
// pages/index.js
export async function getServerSideProps() {
try {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data,
},
};
} catch (error) {
return {
redirect: {
destination: '/500',
permanent: false,
},
};
}
}
export default function Home({ data }) {
return (
<div>
<h1>Home Page</h1>
<p>{data.message}</p>
</div>
);
}
4. Using Middleware for Error Handling
Next.js allows you to use middleware to handle errors globally. Middleware can intercept requests and responses, enabling you to log errors, redirect users, or modify responses.
// middleware.js
export function middleware(req, res) {
try {
// Handle the request
} catch (error) {
res.status(500).json({ message: 'Internal Server Error' });
}
}
Secrets and Hidden Facts
- Custom Error Boundaries: You can create custom error boundaries using React’s
ErrorBoundary
component to catch errors in your components. - Error Logging: Use tools like Sentry or LogRocket to log errors and monitor your application in real-time.
- Error Recovery: Provide users with options to recover from errors, such as retrying a failed request or navigating back to a safe page.
Conclusion
Error handling is an essential part of building robust and user-friendly web applications. Next.js provides built-in support for error handling, allowing you to create custom error pages and handle errors gracefully. By implementing proper error handling, you can improve the user experience and ensure your application runs smoothly.

No comments: