I can't figure out how to handle auth error in my authMiddleware function.
Here is my authMiddleware
function with traditional express way error handling.
const jwt = require('jsonwebtoken');
const { appConfig } = require('../config');
function authMiddleware(req, res, next) {
let token;
const parts = req.headers.authorization.split(' ');
if (parts.length === 2) {
const schema = parts[0];
const credentials = parts[1];
if (/^Bearer$/i.test(schema)) {
token = credentials;
} else {
// throw new Error();
next(new Error('credentials_bad_scheme: Format is Authorization: Bearer [token]'));
}
}
try {
const { user } = jwt.verify(token, appConfig.JWT_SCERET);
req.user = user;
} catch (error) {
// console.log(error);
next(error);
}
next();
}
exports.authMiddleware = authMiddleware;
But with apollo-server-express
and graphql
system. The error
passed into next
function does not work fine. Which means it seems the express
error handling way is not working any more when use graphql
tool stack.
The error
in authMiddleware
will not pass below express error handling middleware
app.use((err, req, res) => {
console.log('error handler: ', err);
});
If I use return res.status(401).json({code: 1001, msg: 'Authorization failed'})
or throw new Error('xxx')
in catch
when auth failed. The request will stop here forever which means will never go down to graphqlExpressHandler
. In order to let request go down to graphqlExpressHandler
, only thing I can do for the errors is to use console.log
to print them.
And there is no way to use express-jwt
unless
method or credentialsRequired
property. Because when use graphql, there is only one route named '/graphql'. So, you can't unless /graphql route
One way to solve this is: make restful api for auth
and handle it in traditonal way. Make graphql
api for data query.