Next.js Discord

Discord Forum

Error handling in middleware

Answered
Cinnamon posted this in #help-forum
Open in Discord
CinnamonOP
I'm using middleware to prevent unauthenticated requests. To do that it makes a request to check if session is authenticated.
I want to know how to handle error thrown while this request since the global-error.js didn't catch the error.

// middleware.ts
try {
  res = await fetch(`checktherequest`);
} catch (e) {
  throw Error('Failed to check the request');
}

// global-error.tsx
'use client';

import React from 'react';

export default function GlobalError({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <html>
      <body>
        <h2>Something went wrong!</h2>
        <button onClick={() => reset()}>Try again</button>
      </body>
    </html>
  );
}

Now it shows the error on the default error boundary
Answered by joulev
Middleware is not part of the app router rendering process - there are no react components involved here so no error boundaries are triggered. You have to try/catch and ensure your middleware doesn’t throw
View full answer

3 Replies