I have a middleware checking if the user is logged in via firebase. If firebase wasn't able to authorize the user, it sends a message with a 403 status code.
Here's my code:
import { NextFunction, Request, Response } from "express";
import firebase from "../config/firebase/index";
async function authMiddleware(req: Request, res: Response, next: NextFunction) {
const headerToken = req.headers.authorization;
if (!headerToken) {
return res.send({ message: "No token provided" }).status(401);
}
if (headerToken && headerToken.split(" ")[0] !== "Bearer") {
res.send({ message: "Invalid token" }).status(401);
}
const token = headerToken.split(" ")[1];
try {
await firebase.auth().verifyIdToken(token);
next();
} catch (error) {
res.send({ message: "Could not authorize" }).status(403);
}
}
export = authMiddleware;
When I make a request to a route, this middleware gets called. I tried sending over a faulty jwt and the response I got was message: "Could not authorize", but the status code was 200 instead of 403.
When I change the return status code to 401 the response gives the correct 401 status.
What am I doing wrong, and how can I make the status code be 403? (I tried in postman and chrome)
CodePudding user response:
The send() method returns response with default status of 200 before the status(403) updates it. You must use status() before sending response to set the status:
res.status(403).send({ message: "Could not authorize" });
