Home > database >  Express.js. Route level middleware is not getting called
Express.js. Route level middleware is not getting called

Time:07-11

I have an API made with Express.js and TypeScript. It works completely fine except that middleware is not getting called - routing request passed successfully to the handler, but middleware is not getting involved at all.

Here is how 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;

Here is how middleware is defined:

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;

CodePudding user response:

Because of its first argument, authMiddleware is error-handling middleware, which is called only if an error has occurred before and propagated with next(error).

But looking at the code of authMiddleware, it seems that you do not need the error argument at all. So you should simply omit it:

const authMiddleware = (req: Request, res: Response, next: NextFunction): void => {
 ...
};
  • Related