Bird
Raised Fist0
GraphQLquery~10 mins

Context setup in GraphQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Context setup
Start GraphQL Request
↓
Initialize Context Object
↓
Attach Context to Request
↓
Resolver Accesses Context
↓
Resolver Uses Context Data
↓
Return Response with Context Data
This flow shows how a context object is created and passed to GraphQL resolvers during a request, allowing shared data access.
Execution Sample
GraphQL
const context = ({ req }) => {
  return { user: req.user };
};

// Resolver example
resolve(parent, args, context) {
  return context.user.id;
}
This code sets up a context function that extracts user info from the request and makes it available to resolvers.
Execution Table
StepActionInputContext StateResolver AccessOutput
1Receive request{ user: { id: 42 } }{}N/AN/A
2Initialize contextreq.user = { id: 42 }{ user: { id: 42 } }N/AN/A
3Pass context to resolvercontext = { user: { id: 42 } }{ user: { id: 42 } }context.user.id42
4Resolver returns dataN/A{ user: { id: 42 } }context.user.id42
5Send response42{ user: { id: 42 } }N/A{ data: 42 }
💡 Request completes after resolver returns user id from context.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
context{}{ user: { id: 42 } }{ user: { id: 42 } }{ user: { id: 42 } }
resolverOutputN/AN/A4242
Key Moments - 2 Insights
Why does the resolver receive the context object?
The resolver receives the context so it can access shared data like the authenticated user, as shown in step 3 of the execution_table.
What happens if the context is not initialized properly?
If context is empty or missing user data, resolvers cannot access needed info, causing errors or missing data, as seen if context stayed {} after step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of context after step 2?
A{ user: { id: 42 } }
B{}
Cundefined
Dnull
💡 Hint
Check the 'Context State' column at step 2 in the execution_table.
At which step does the resolver access the user id from context?
AStep 1
BStep 3
CStep 5
DStep 2
💡 Hint
Look at the 'Resolver Access' column in the execution_table.
If the request had no user info, what would context likely be after step 2?
A{ user: { id: 42 } }
B{ user: null }
C{}
Dundefined
💡 Hint
Context is initialized from request data; missing user means empty context as shown in variable_tracker.
Concept Snapshot
Context setup in GraphQL:
- Context is an object created per request
- It holds shared data like authenticated user
- Passed automatically to all resolvers
- Enables resolvers to access request-specific info
- Setup via a function returning context object
Full Transcript
In GraphQL, context setup means creating an object that holds shared data for each request, like the logged-in user. When a request comes in, the server runs a context function that extracts needed info from the request and returns it as the context object. This context is then passed to every resolver function. Resolvers use this context to access data like user ID or permissions. The execution flow starts with receiving the request, initializing context, passing it to resolvers, and finally returning the response. If context is missing or empty, resolvers cannot access necessary data, which can cause errors. This visual trace shows step-by-step how context is created and used during a GraphQL request.

Practice

(1/5)
1. What is the main purpose of the context in a GraphQL server?
easy
A. To share data like user info or database clients across all resolvers
B. To define the GraphQL schema types
C. To write the query resolvers
D. To format the GraphQL query response

Solution

  1. 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.
  2. Step 2: Compare with other options

    Defining schema types, writing resolvers, and formatting responses are separate tasks not handled by context.
  3. Final Answer:

    To share data like user info or database clients across all resolvers -> Option A
  4. Quick Check:

    Context shares data across resolvers [OK]
Hint: Context shares common data across resolvers per request [OK]
Common Mistakes:
  • Confusing context with schema definition
  • Thinking context formats responses
  • Assuming context writes resolver logic
2. Which of the following is the correct way to define a context function in Apollo Server?
easy
A. context = { user: getUser() }
B. context: () => ({ user: getUser() })
C. context: { user: getUser() }
D. context() { return user: getUser() }

Solution

  1. Step 1: Recall Apollo Server context syntax

    Context is defined as a function returning an object, e.g., context: () => ({ user: getUser() }).
  2. 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.
  3. Final Answer:

    context: () => ({ user: getUser() }) -> Option B
  4. Quick Check:

    Context is a function returning an object [OK]
Hint: Context must be a function returning an object [OK]
Common Mistakes:
  • Defining context as a plain object
  • Missing parentheses in function syntax
  • Using assignment instead of property
3. Given this context setup in Apollo Server:
context: () => ({ user: { id: 5, name: 'Alice' } })

What will be the value of context.user.name inside a resolver?
medium
A. undefined
B. 5
C. null
D. 'Alice'

Solution

  1. Step 1: Analyze the context object

    The context function returns an object with a user property containing { id: 5, name: 'Alice' }.
  2. Step 2: Access user.name in resolver

    Accessing context.user.name will give the string 'Alice' as defined.
  3. Final Answer:

    'Alice' -> Option D
  4. Quick Check:

    context.user.name = 'Alice' [OK]
Hint: Context returns user object; access properties directly [OK]
Common Mistakes:
  • Confusing user id with name
  • Assuming context is undefined
  • Expecting null instead of string
4. You wrote this context function:
context: () => { user: getUser() }

Why does context.user return undefined in resolvers?
medium
A. Because user is not a valid property
B. Because getUser() is undefined
C. Because the function does not return the object explicitly
D. Because context must be an object, not a function

Solution

  1. Step 1: Check function return behavior

    The function uses curly braces but lacks a return statement, so it returns undefined by default.
  2. Step 2: Understand impact on context

    Since nothing is returned, context.user is undefined in resolvers.
  3. Final Answer:

    Because the function does not return the object explicitly -> Option C
  4. Quick Check:

    Missing return in function = undefined context [OK]
Hint: Use return or parentheses to return object in arrow function [OK]
Common Mistakes:
  • Omitting return in arrow function with braces
  • Assuming getUser() is undefined without checking
  • Thinking context must be an object, not function
5. You want to add a database client and user info to context for each request. Which is the best way to do this in Apollo Server?
hard
A. context: async () => { const db = await connectDB(); const user = await getUser(); return { db, user }; }
B. context: { db: connectDB(), user: getUser() }
C. context: () => { db: connectDB(); user: getUser(); }
D. context: () => ({ db: connectDB(), user: getUser() })

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    context: async () => { const db = await connectDB(); const user = await getUser(); return { db, user }; } -> Option A
  4. Quick Check:

    Async context with awaited data [OK]
Hint: Use async function and await for async data in context [OK]
Common Mistakes:
  • Not awaiting async calls in context
  • Using plain object instead of function
  • Missing return statement in function
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard