Currently, I am facing an issue with my Express.js and TypeScript API. Although the API is working smoothly, it seems that the middleware is not being triggered. The routing requests are successfully passed to the handler without involving the middleware at all.
Below is how the routes are defined:
class TagsRoute implements Routes {
public path = '/tags';
public router = Router();
public tagsController = new TagsController();
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}`, this.tagsController.getTagPosts);
this.router.get(`${this.path}/read`, this.tagsController.getTags);
this.router.post(`${this.path}`, authMiddleware, this.tagsController.addTag);
this.router.delete(`${this.path}`, authMiddleware, this.tagsController.deleteTag);
this.router.put(`${this.path}`, authMiddleware, this.tagsController.editTag);
}
}
export default TagsRoute;
The middleware definition is as follows:
const authMiddleware = (error: HttpException, req: Request, res: Response, next: NextFunction): void => {
try {
if (
req.headers.authorization &&
req.headers.authorization.split(' ')[0] === 'Bearer'
) {
const token = req.headers.authorization.split(' ')[1];
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
getAuth()
.verifyIdToken(token)
.then((decodedToken) => {
if (!decodedToken || decodedToken.exp < Date.now()) {
res.status(401).json({ message: "Invalid token" });
}
next()
})
.catch((error) => {
res.status(401).json({message: "Invalid token"});
});
}
} catch (error) {
next(error);
}
};
export default authMiddleware;