What is Context in Resolver in GraphQL Explained
context is an object passed to every resolver that holds shared data like authentication info, database connections, or user details. It acts like a shared workspace allowing resolvers to access common resources during query execution.How It Works
Imagine you are at a restaurant and the waiter (resolver) needs to know your preferences or allergies to serve you properly. Instead of asking you repeatedly, the waiter has a note (context) with all your important info. In GraphQL, context is this note shared with every resolver during a query.
This context object is created once per request and passed down to all resolvers. It can hold things like the logged-in user’s info, database connections, or other utilities. This way, resolvers don’t need to fetch or pass these details individually, making the code cleaner and more efficient.
Example
context carries the current user info to resolvers.const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { currentUserName: String } `; const resolvers = { Query: { currentUserName: (parent, args, context) => { // Access user info from context return context.user ? context.user.name : null; } } }; // Simulate user authentication const server = new ApolloServer({ typeDefs, resolvers, context: () => { // This user info would normally come from a token or session return { user: { id: '123', name: 'Alice' } }; } }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
When to Use
Use context whenever you need to share data or services across multiple resolvers during a single GraphQL request. Common uses include:
- Passing authentication or user info to check permissions
- Sharing database or API clients to avoid reconnecting
- Storing request-specific data like locale or headers
This helps keep resolvers simple and focused on fetching data without worrying about setup details.
Key Points
- Context is created once per request and shared with all resolvers.
- It holds common data like user info, database connections, or utilities.
- Resolvers receive
contextas a third argument. - Using
contextkeeps your code clean and avoids repetition.