How to Use Context for Authentication in GraphQL
In GraphQL, use the
context object to pass authentication information like user tokens or user data to resolvers. This allows resolvers to check if a user is authenticated before returning data. You typically add authentication logic in the server setup to decode tokens and attach user info to context.Syntax
The context is an object passed to every resolver in a GraphQL server. It usually contains authentication data like the current user.
Typical syntax in a GraphQL server setup:
context: ({ req }) => { ... }— a function that receives the HTTP request.- Inside, extract the token from headers.
- Verify the token and add user info to
context. - Resolvers access
context.userto check authentication.
javascript
const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const token = req.headers.authorization || ''; const user = getUserFromToken(token); // your function to verify token return { user }; } });
Example
This example shows a simple Apollo Server setup where the context extracts a user from a token and resolvers check if the user is authenticated before returning data.
javascript
const { ApolloServer, gql } = require('apollo-server'); // Sample type definitions const typeDefs = gql` type Query { secretData: String } `; // Mock function to decode token function getUserFromToken(token) { if (token === 'valid-token') { return { id: 1, name: 'Alice' }; } return null; } // Resolvers check context.user const resolvers = { Query: { secretData: (parent, args, context) => { if (!context.user) { throw new Error('Not authenticated'); } return `Secret info for ${context.user.name}`; } } }; const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const token = req.headers.authorization || ''; const user = getUserFromToken(token); return { user }; } }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Output
Server ready at http://localhost:4000/
Common Pitfalls
Common mistakes when using context for authentication include:
- Not extracting the token correctly from request headers.
- Failing to verify the token before adding user info to context.
- Not handling missing or invalid tokens, causing server errors.
- Trying to access
context.userwithout checking if it exists.
Always validate tokens and handle errors gracefully.
javascript
/* Wrong way: No token verification, context.user always set */ context: ({ req }) => { const token = req.headers.authorization || ''; // No verification return { user: { id: 1, name: 'FakeUser' } }; } /* Right way: Verify token and set user only if valid */ context: ({ req }) => { const token = req.headers.authorization || ''; const user = getUserFromToken(token); return { user }; }
Quick Reference
Tips for using context in GraphQL authentication:
- Extract token from
req.headers.authorization. - Verify token securely before trusting user data.
- Add user info to
contextfor access in resolvers. - Check
context.userin resolvers to enforce authentication. - Handle missing or invalid tokens gracefully.
Key Takeaways
Use the context function to pass authenticated user info to resolvers.
Always verify tokens before adding user data to context.
Access context.user in resolvers to check authentication status.
Handle missing or invalid tokens to avoid server errors.
Keep authentication logic centralized in the context setup.