I have an express app. I am adding a middleware which redirects user to logout if token is invalid.
export async function validateAuthTokenMiddleware(
req: Request,
res: Response,
next: NextFunction,
): Promise<NextFunction | void> {
try {
const { context } = req;
await validateToken(context);
next();
} catch (err) {
logoutAndRedirectUser(res);
}
}
Code for logoutAndRedirectUser
const logoutUser = (res: Response) => {
res.clearCookie('my_token')
res.format({
json: () =>
res.status(401).json({
errors: [
{
message: 'You must login to see this',
errorCode: '0001',
},
],
extensions: {
location: location,
},
}),
html: () => res.redirect(302, location),
default: () => res.redirect(302, location),
});
};
I am using this middleware in my route like so. All api request from client goes via this route:
router.use('/api', validateAuthTokenMiddleware, graphql);
However the redirect is not working as expected.
/api call and browser remains on same page. res.redirect(302, '/login') is not triggered.logoutUser to just send res.redirect(302, '/login') Instead of res.json. Still doesn't work.My browser makes simple requests with
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,...
This means that application/json is acceptable (because of */*;q=0.8), therefore your json response is chosen, which is not a redirect. Perhaps reordering the choices within res.format helps.
You wrote:
I have tried refactoring logoutUser to just send res.redirect(302, '/login') Instead of res.json. Still doesn't work.
Can you share your refactored code as well, please?
I end up setting a condition on my Client code. If received 401, redirect to login page.