Learn how to handle errors effectively in Next.js

In Next.js, error handling can be implemented using a combination of built-in features and custom error handling techniques. Here are some approaches you can take to handle errors in Next.js:

Error Boundaries

Next.js supports React’s Error Boundary concept, which allows you to catch errors in the component tree and display a fallback UI instead of a complete application crash. You can create an error boundary component using the “componentDidCatch” lifecycle method or the “static getDerivedStateFromError” method and wrap the components where you want to enable error handling with the ErrorBoundary component.

import React from 'react';

class ErrorBoundary extends React.Component {
  state = {
    hasError: false,
  };

  componentDidCatch(error, errorInfo) {
    // Handle the error and update state
    this.setState({ hasError: true });
    // You can also log the error or send it to an error tracking service
    console.error(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // Render a fallback UI when an error occurs
      return <p>Something went wrong.</p>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Custom Error Pages

Next.js allows you to define custom error pages to handle different types of errors, such as 404 (not found) or 500 (server error). To create a custom error page, create a file with the specific error status code in the “pages” directory. For example:

  • “pages/404.js” for handling 404 errors.
  • “pages/500.js” for handling 500 errors.

By creating these custom error pages, you can provide a more user-friendly and tailored experience when errors occur.

import React from 'react';

const Custom404 = () => {
  return <h1>404 - Page Not Found</h1>;
};

export default Custom404;

Error Handling Middleware (API Routes)

For error handling in Next.js API routes, you can utilize middleware functions to intercept and handle errors. Middleware allows you to perform common tasks, such as error logging or returning specific error responses. Here’s an example of an error handling middleware for API routes

const errorHandler = (handler) => async (req, res) => {
  try {
    await handler(req, res);
  } catch (error) {
    // Handle the error and send an appropriate response
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const myRouteHandler = (req, res) => {
  // Your API route logic
};

export default errorHandler(myRouteHandler);

In this example, the “errorHandler” middleware wraps the API route handler function. If an error occurs within the handler, it will be caught, logged, and a 500 response will be sent to the client.

Leave a comment