I have a graphql endpoint which is authorised by a JWT. My JWT strategy verifies the JWT then adds the user object to the request object.
In a restful route, I would access my users' data like so:
router.get('/', (req, res, next) => {
console.log('user', req.user)
}
I want to access req.user object within my graphql resolver in order to extract the users' ID. However, when I try log the context
variable, it is always empty.
Do I need to configure my graphql endpoint to pass through the req
data to the resolver?
My app.js has my graphql set up like this:
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
app.use('/graphql', [passport.authenticate('jwt', { session: false }), bodyParser.json()], graphqlExpress({ schema }));
Then I have my resolvers like so:
const resolvers = {
Query: {
user: async (obj, {email}, context) => {
console.log('obj', obj) // undefined
console.log('email', email) // currently passed through in graphql query but I want to replace this with the user data passed in req / context
console.log('context', context) // {}
return await UserService.findOne(email)
},
};
// Put together a schema
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
How can I access my JWT user data in my resolvers?
Apparently you need to pass through context manually like so:
app.use('/graphql', [auth_middleware, bodyParser.json()], (req, res) => graphqlExpress({ schema, context: req.user })(req, res) );
Found the answer here if anybody is interested:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With