In my middleware I have a generic unauthorized function that handles returning responses based on the request's "accept" header. For example, a request that expects json will get json, but a request that expects html will get a 302 back to the web home page, etc. In my middleware handlers, I've destructured the context, so now when it comes to invoking my unauthorized helper, I have to explicitly pass in things that I may need, like the request, the redirect helper, etc, and that seems a bit messy. I'm hoping to get some ideas on how to approach this better. Some example code
const unauthorized = (request: Request, redirect: AstroSharedContext['redirect']) => {
if (request.headers.get('accept')?.includes('application/json')) {
return new Response(
JSON.stringify({
error: 'invalid_token',
error_description: 'The access token is missing, invalid, or expired'
}),
{
status: 401,
headers: {
'Content-Type': 'application/json',
'WWW-Authenticate':
'Bearer error="invalid_token", error_description="The access token is missing, invalid, or expired"'
}
}
);
} else {
return redirect('/', 302);
}
};
const ensureAuthenticated = defineMiddleware(async ({ url, locals, redirect, request }, next) => {
const authenticatedRoutes = ['/protected', '/auth/logout', '/api/customer'];
if (authenticatedRoutes.some((route) => url.pathname.startsWith(route))) {
if (!locals.authenticated) {
return unauthorized(request, redirect);
}
}
return next();
});