Blog>
Snippets

Next.js Middleware Error Handling

Show how to create and use Next.js middleware with proper error handling to intercept requests and manage errors before reaching the API routes or pages.
// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  try {
    // Perform your checks here, for example, Auth check
    // If everything is OK, continue with the request
    return NextResponse.next();
  } catch (error) {
    // Handle any error that occurred during the checks
    // You can return a custom error response or status code
    const customResponse = new Response('An error occurred', { status: 500 });
    return customResponse;
  }
}
This is a middleware file named 'middleware.js'. It exports a function that takes a request object, performs some checks, and either allows the request to continue or returns a custom error response if an exception occurs.
// next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*', 
        destination: '/api/:path*', // Matched parameters can be used in the destination
      }
    ];
  }
};
This is a 'next.config.js' configuration file where rewrites are defined for API routes. This setup is necessary for the middleware to apply to requests going to '/api/*' pattern URLs.
// pages/api/example.js
export default function handler(req, res) {
  try {
    // Handle the API logic
    res.status(200).json({ message: 'Success' });
  } catch (error) {
    // Handle errors that occur within the API Route
    res.status(500).json({ error: 'Internal Server Error' });
  }
}
This is an example API route named 'example.js'. Inside the handler function, the try-catch block deals with potential errors that could occur when processing the request, returning a success response or an error response accordingly.
body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.error-message {
  color: red;
  font-weight: bold;
}
This is a CSS snippet to style the body of the document and any element with the class 'error-message'. 'error-message' is styled to have red, bold text.