How to handle errors in Next.js



Image not found!!

In Next.js, error handling can be done at different levels, including handling errors during server-side rendering (SSR), client-side rendering (CSR), and static site generation (SSG). Here are some common approaches for handling errors in Next.js:

1. Custom Error Page:

Next.js allows you to create custom error pages for different HTTP error status codes. You can create pages with the following naming convention:

  • _error.js for generic errors.
  • 404.js for 404 errors.

Example of a custom error page (_error.js):

jsx
// pages/_error.js const ErrorPage = ({ statusCode }) => { return ( <div> <p> {statusCode ? `An error ${statusCode} occurred on server` : 'An error occurred on client'} </p> </div> ); }; ErrorPage.getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 404; return { statusCode }; }; export default ErrorPage;

2. Error Boundary Component:

You can use React's error boundaries to catch JavaScript errors anywhere in your component tree. To implement this, you can use the componentDidCatch lifecycle method or the ErrorBoundary component.

Example of an error boundary component:

jsx
// components/ErrorBoundary.js import React, { Component } from 'react'; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { logErrorToService(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } export default ErrorBoundary;

Then, you can wrap your pages or components with this error boundary:

jsx
// pages/_app.js import ErrorBoundary from '../components/ErrorBoundary'; function MyApp({ Component, pageProps }) { return ( <ErrorBoundary> <Component {...pageProps} /> </ErrorBoundary> ); } export default MyApp;

3. API Route Error Handling:

If you're working with API routes, you can handle errors by sending the appropriate HTTP status codes and error messages.

Example of an API route:

jsx
// pages/api/example.js export default async function handler(req, res) { try { // Your API logic here if (somethingWentWrong) { res.status(500).json({ error: 'Internal Server Error' }); } else { res.status(200).json({ data: 'Success' }); } } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }

These are just a few approaches to handling errors in Next.js. The approach you choose may depend on your specific use case and the type of errors you need to handle.