utdev
utdev

Reputation: 4102

Express Typescript does not use Middleware

I built a simple Auth Middleware but somehow the middleware does not get called at all, if I for instance throw an Error inside my middle function it just gets ignored nothing get printed.

I only need to call the auth middleware on the route below, just for test purposes.

My UserRoutes.ts

import auth from '../middleware/auth';

export default class UserRoutes {

  public UserController: UserController = new UserController();

  public routes(app: Application): void {
    // ...
    app.route('/api/users/me')
      .get(this.UserController.me, auth); // this is where I call my auth middleware
}

In my middleware I basically trim the Bearer Space and try to find the correct user from the token which I get after I log in. The tokens are saved correctly to my mongodb.

My auth middleware looks like this:

const auth = async (req: IUserRequest, res: Response, next: NextFunction) => {
  const token = req.header('Authorization').replace('Bearer ', '');
  const msg = { auth: false, message: 'No token provided.' };

  if (!token) res.status(500).send(msg);

  try {
    const data: any = jwt.verify(token, JWT_KEY);
    const user = await User.findOne({ _id: data._id, 'tokens.token': token });

    if (!user) {
      throw new Error("Could not find User");
    }

    req.user = user;
    req.token = token;
    next();
  } catch (error) {
    res.status(401).send({ error: 'Not authorized to access this resource.' });
  }
}

export default auth;

UserController.ts:

export class UserController {
   ///...
   public me(req: IUserRequest, res: Response) {
     res.send(req.user)
   }
}

Upvotes: 0

Views: 469

Answers (1)

jfriend00
jfriend00

Reputation: 707326

Well, your me method is the first handler called and sends a response and ends all processing. No further routes will be called. For a middleware to actually behave as a middleware and do something, but then let other routes continue to be called, it needs to:

  1. Not send a response. Technically it could, but then there would be no point to the subsequent routes since you can only send done response per request.
  2. Call next() which is the third argument passed to it (which you haven't declared) when it is done with its processing and it wishes for routing to continue.

So, because me() is first and it ends all routing, your auth() handler is never called. Perhaps you meant to put the auth() handler first? Routes are executed in the order they are registered in the code (assuming they match the current incoming URL).

Upvotes: 1

Related Questions