1

In every request I send token, and check it in express middleware

app.use(async (req, res, next) => {
  const authorization = req.headers.authorization;
  let token = null;
  let user;

  if (authorization) {
    try {
      token = jwt.verify(authorization, config.secret);
    } catch (e) {
     // dont work
      throw new GraphQLError({ message: 'token damaged' });
    }

    if (token) {
      const { _id } = token;

      user = await User.findOne({ _id });
    }

    if (user) {
      req.user = user;
    }
  }

  next();
});

Token can be damaged, and I do the check:

try {
      token = jwt.verify(authorization, config.secret);
    } catch (e) {
      throw new GraphQLError({ message: 'token damaged' });
    }

So I need to send to client application Express Error, but it dont work, as expected, are there any options to create graphql middlewares which take request arguments before calling every resolver? Now if I want throw error of damaged token I need write check in every resolver?

Khotey Vitaliy
  • 509
  • 1
  • 6
  • 18

1 Answers1

1

You can simply respond and return, without calling the next middleware:

try {
  token = jwt.verify(authorization, config.secret);
} catch (e) {
  res.statusCode = 401;
  return res.end('{"errors": [{"message": "token damaged"}]}');
}
Nir Levy
  • 12,750
  • 3
  • 21
  • 38