#How to throw an error from a middleware?

4 messages · Page 1 of 1 (latest)

hidden venture
#

I'm trying to use Astro's middleware functionality to do an Authentication for every page load.

My question is how do you throw an error from the middleware? Let's say the user is unauthorized. What do we do within the middleware function?

Astro provides this snippet on the docs, but nothing about how to handle errors and status codes.

async function auth(_, next) {
  console.log("auth request");
  const response = await next();
  console.log("auth response");
  return response;
}

Thanks!

lavish raft
#

not sure what you mean by throw an error. usually if a user in unauthenticated, you'd redirect them to the login portal. if a user is unauthorised to access a certain route, you'd handle that in the page to show a contextual error, or redirect them to something else

#

Astro provides this snippet on the docs, but nothing about how to handle errors and status codes.
middleware must return a response, but it doesn't matter if that's from next() or if you create a Response object yourself.

pine garnet
#

Hi @hidden venture !

We use middleware to check auth on routes as well. What we do is basically just redirect to the login as @lavish raft here mentioned, like:

 return Response.redirect(`${RequestURL.origin}/login`);

RequestURL.origin for us is there because we have 3 app stages running on a single codebase, so we need to redirect to the appropriate subdomain.