Node.js › GraphQL with Node.js
How would you implement authentication and authorization in a GraphQL API, given all requests typically go through a single endpoint?
AdvancedAnswer
Since GraphQL typically exposes just one HTTP endpoint (unlike REST's many distinct routes), authentication is usually handled once via a context function that runs for every request -- extracting and verifying a token, then making the resulting user object available to every resolver via the shared 'context' argument -- while authorization (checking whether the authenticated user is allowed to access a specific field or perform a specific mutation) happens inside individual resolvers, or via a reusable directive applied declaratively in the schema itself.
const server = new ApolloServer({
typeDefs, resolvers,
context: async ({ req }) => {
const token = req.headers.authorization?.replace('Bearer ', '');
const user = token ? await verifyToken(token) : null;
return { user };
},
});
const resolvers = {
Mutation: {
deletePost: (_, { id }, { user }) => {
if (!user || user.role !== 'admin') throw new Error('Forbidden');
return db.posts.delete(id);
},
},
};Real-world example A GraphQL API verifies the incoming JWT once inside its context function on every request, making the resulting authenticated user object available to all resolvers via context.user, letting individual resolvers implement fine-grained authorization checks (like restricting a deletePost mutation to admins) without each one needing to re-parse or re-verify the token itself.