How to Use Context in Apollo Server for Request Data
In Apollo Server, use the
context option to pass data like authentication info or database connections to all resolvers. This context is a function or object that runs on each request, providing shared data accessible in resolver functions via the third argument.Syntax
The context option in Apollo Server is set when creating the server instance. It can be a function that receives the request and returns an object accessible in resolvers.
Parts explained:
context: ({ req }) => { ... }- a function receiving the HTTP request.- Return an object with any data you want available in resolvers.
- Resolvers receive this object as the third argument.
javascript
const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { // Extract token or user info from request headers const token = req.headers.authorization || ''; return { token }; } });
Example
This example shows how to pass an authorization token from the HTTP headers into the context and access it inside a resolver.
javascript
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { currentToken: String } `; const resolvers = { Query: { currentToken: (parent, args, context) => { return context.token || 'No token provided'; } } }; const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const token = req.headers.authorization || ''; return { token }; } }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Output
Server ready at http://localhost:4000/
Common Pitfalls
Common mistakes when using context include:
- Not returning an object from the
contextfunction, causing resolvers to getundefined. - Trying to access
contextdata in resolvers without including it as a parameter. - Not handling missing headers or tokens gracefully.
Always ensure your context function returns an object and your resolvers accept the context argument.
javascript
/* Wrong way: context function returns nothing */ const serverWrong = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const token = req.headers.authorization; // Missing return statement } }); /* Right way: return an object */ const serverRight = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const token = req.headers.authorization || ''; return { token }; } });
Quick Reference
Tips for using context in Apollo Server:
- Use
contextto share data like auth info, database clients, or loaders. - It runs on every request, so keep it fast and stateless.
- Access
contextin resolvers as the third argument:resolver(parent, args, context). - Always return an object from the
contextfunction.
Key Takeaways
Use the
context option in Apollo Server to pass shared data to resolvers on each request.The
context function receives the request and must return an object accessible in resolvers.Access
context inside resolvers as the third argument to use shared data like auth tokens.Always return an object from the
context function to avoid undefined errors.Keep
context creation fast and stateless since it runs on every request.