Context setup helps share information like user details or database connections across all parts of a GraphQL server.
Context setup in GraphQL
const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { // create and return context object return { user: getUserFromReq(req), db }; } });
The context function runs for every request and returns an object shared by all resolvers.
You can add anything to context like user info, database clients, or helpers.
context: () => ({ db: myDatabaseClient })context: ({ req }) => {
const user = authenticate(req.headers.authorization);
return { user };
}context: async ({ req }) => { const user = await getUserFromToken(req.headers.token); return { user }; }
This example sets up a GraphQL server with context that reads user info from request headers. The query returns the current user's name or 'Guest' if no user is found.
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { currentUserName: String } `; const resolvers = { Query: { currentUserName: (parent, args, context) => { return context.user ? context.user.name : 'Guest'; } } }; function getUserFromReq(req) { // Simulate user extraction if (req.headers.authorization === 'secret-token') { return { name: 'Alice' }; } return null; } const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const user = getUserFromReq(req); return { user }; } }); // Simulate a request with authorization header const fakeReq = { headers: { authorization: 'secret-token' } }; server.executeOperation({ query: '{ currentUserName }', contextValue: server.context({ req: fakeReq }) }).then(response => { console.log(response.data.currentUserName); });
Context runs once per request, so avoid putting heavy operations inside it.
Always return a plain object from context for easy access in resolvers.
You can pass extra info like loaders or helpers in context to keep resolvers clean.
Context shares data like user info or database clients across all resolvers.
It runs once per request and returns an object accessible in every resolver.
Use context to keep your GraphQL server organized and secure.
Practice
context in a GraphQL server?Solution
Step 1: Understand what context provides
Context is an object that runs once per request and is accessible in every resolver, allowing shared data like user info or database clients.Step 2: Compare with other options
Defining schema types, writing resolvers, and formatting responses are separate tasks not handled by context.Final Answer:
To share data like user info or database clients across all resolvers -> Option AQuick Check:
Context shares data across resolvers [OK]
- Confusing context with schema definition
- Thinking context formats responses
- Assuming context writes resolver logic
Solution
Step 1: Recall Apollo Server context syntax
Context is defined as a function returning an object, e.g.,context: () => ({ user: getUser() }).Step 2: Identify syntax errors in other options
context = { user: getUser() } uses assignment instead of a function, C uses an object directly without a function, and D has invalid syntax missing parentheses and braces.Final Answer:
context: () => ({ user: getUser() }) -> Option BQuick Check:
Context is a function returning an object [OK]
- Defining context as a plain object
- Missing parentheses in function syntax
- Using assignment instead of property
context: () => ({ user: { id: 5, name: 'Alice' } })What will be the value of
context.user.name inside a resolver?Solution
Step 1: Analyze the context object
The context function returns an object with auserproperty containing{ id: 5, name: 'Alice' }.Step 2: Access
Accessinguser.namein resolvercontext.user.namewill give the string 'Alice' as defined.Final Answer:
'Alice' -> Option DQuick Check:
context.user.name = 'Alice' [OK]
- Confusing user id with name
- Assuming context is undefined
- Expecting null instead of string
context: () => { user: getUser() }Why does
context.user return undefined in resolvers?Solution
Step 1: Check function return behavior
The function uses curly braces but lacks a return statement, so it returns undefined by default.Step 2: Understand impact on context
Since nothing is returned,context.useris undefined in resolvers.Final Answer:
Because the function does not return the object explicitly -> Option CQuick Check:
Missing return in function = undefined context [OK]
- Omitting return in arrow function with braces
- Assuming getUser() is undefined without checking
- Thinking context must be an object, not function
Solution
Step 1: Understand async context needs
Connecting to a database and fetching user info are asynchronous operations, so context must be async and await these calls.Step 2: Evaluate options for async correctness
context: async () => { const db = await connectDB(); const user = await getUser(); return { db, user }; } correctly uses async function and awaits results before returning an object. context: { db: connectDB(), user: getUser() } is a plain object, not a function. context: () => { db: connectDB(); user: getUser(); } lacks return and awaits. context: () => ({ db: connectDB(), user: getUser() }) returns an object but does not await async calls.Final Answer:
context: async () => { const db = await connectDB(); const user = await getUser(); return { db, user }; } -> Option AQuick Check:
Async context with awaited data [OK]
- Not awaiting async calls in context
- Using plain object instead of function
- Missing return statement in function
Ready to prove it?
Pass the test and this pattern moves unknown
