You can do something like this in TypeScript which is way cleaner than most of the answers I saw here.
export const parseBearer = (bearer: string) => {
const [_, token] = bearer.trim().split(" ");
return token;
};
Basically truncating the bearer string, splitting by space and then getting the element(token) at the index of one.
To handle the token all you will have to do is to verify it using a package such as jsonwebtoken
. Final result will look something like this:
import jwt from "jsonwebtoken"
const authorizationHeader = req.headers["Authorization"];
const token = parseBearer(authorizationHeader);
try {
const decoded = jwt.verify(token, secret);
return res.json(decoded);
} catch (error: any) {
return res.status(403).json({ error: "Invalid token" });
}