0
0
GraphqlConceptBeginner · 3 min read

What is Context in Resolver in GraphQL Explained

In GraphQL, 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

This example shows a simple GraphQL server where the context carries the current user info to resolvers.
javascript
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}`);
});
Output
Server ready at http://localhost:4000/
🎯

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 context as a third argument.
  • Using context keeps your code clean and avoids repetition.

Key Takeaways

Context is a shared object passed to all resolvers during a GraphQL request.
It commonly holds user info, database clients, and other shared resources.
Resolvers access context as their third argument to get needed data.
Using context simplifies resolver code and supports authentication and data access.
Context is created fresh for each request to keep data isolated and secure.