Context & Resolver Arguments
Resolvers often need things that aren't part of the query: the logged-in user, a database connection, per-request caches, the request locale. Passing them through arguments would be clumsy and insecure, and global variables would leak between users. GraphQL's answer is the context: one object, created fresh for every request, that every resolver receives as its third argument.
Passing a context
In graphql-js you supply it as contextValue. Servers build it from the HTTP request (headers, cookies) before executing:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type User { name: String! }
type Query { me: User, greeting: String! }
`);
const users = { u1: { name: 'Priya' }, u2: { name: 'Tomás' } };
const rootValue = {
// Root-value functions get (args, context, info).
me: (_args, context) => (context.userId ? users[context.userId] : null),
greeting: (_args, { locale, userId }) => {
const name = userId ? users[userId].name : 'guest';
return locale === 'es' ? `¡Hola, ${name}!` : `Hello, ${name}!`;
},
};
// Pretend these came from two different HTTP requests.
const requests = [
{ userId: 'u1', locale: 'en' },
{ userId: 'u2', locale: 'es' },
{ userId: null, locale: 'en' },
];
for (const contextValue of requests) {
const result = await graphql({ schema, rootValue, contextValue, source: '{ me { name } greeting }' });
console.log(JSON.stringify(result.data));
}{"me":{"name":"Priya"},"greeting":"Hello, Priya!"}
{"me":{"name":"Tomás"},"greeting":"¡Hola, Tomás!"}
{"me":null,"greeting":"Hello, guest!"}
The query text was identical; only the context changed. That's how one schema serves every user.
What usually goes into the context
| Entry | Why |
|---|---|
user / viewer |
the authenticated user (decoded from a token), for authorization |
db / services |
data-access objects, so resolvers don't import globals (easier to test) |
loaders |
per-request DataLoaders for batching and caching (later lesson) |
requestId, locale |
logging, tracing and formatting |
Warning: Create a new context per request. Reusing one object across requests means a cache or a
userfrom one person can leak into another person's response.
All four arguments in code-first resolvers
With GraphQLObjectType, every resolver gets (parent, args, context, info). Let's use all of them: a Product.price field that converts currency (args), applies a member discount (context) and reads the base price from its parent:
import {
graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLFloat, GraphQLList,
} from 'graphql';
const rates = { EUR: 1, USD: 1.1, GBP: 0.85 };
const Product = new GraphQLObjectType({
name: 'Product',
fields: {
name: { type: GraphQLString },
price: {
type: GraphQLFloat,
args: { currency: { type: GraphQLString, defaultValue: 'EUR' } },
resolve: (product, { currency }, context, info) => {
context.log.push(`${info.parentType.name}.${info.fieldName} for ${product.name}`);
const discount = context.user?.isMember ? 0.9 : 1;
return Math.round(product.basePrice * rates[currency] * discount * 100) / 100;
},
},
},
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
products: {
type: new GraphQLList(Product),
resolve: () => [{ name: 'Tea', basePrice: 8 }, { name: 'Mug', basePrice: 15 }],
},
},
}),
});
for (const user of [null, { isMember: true }]) {
const contextValue = { user, log: [] };
const result = await graphql({
schema,
contextValue,
source: '{ products { name price(currency: "USD") } }',
});
console.log(JSON.stringify(result.data.products), contextValue.log.length, 'price lookups');
}[{"name":"Tea","price":8.8},{"name":"Mug","price":16.5}] 2 price lookups
[{"name":"Tea","price":7.92},{"name":"Mug","price":14.85}] 2 price lookups
The info argument
info describes where the resolver is in the query. Most resolvers ignore it, but it's useful for logging, tracing and advanced optimizations (like selecting only the requested database columns):
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Author { name: String, bio: String, born: Int }
type Query { author: Author }
`);
const rootValue = {
author: (_args, _context, info) => {
const selected = info.fieldNodes[0].selectionSet.selections.map((s) => s.name.value);
console.log('field:', info.fieldName);
console.log('return type:', String(info.returnType));
console.log('operation:', info.operation.operation, info.operation.name?.value);
console.log('client selected:', selected.join(', '));
// A real resolver could now run: SELECT name, born FROM authors ...
return { name: 'Chimamanda Ngozi Adichie', bio: '…', born: 1977 };
},
};
const result = await graphql({ schema, rootValue, source: 'query AuthorCard { author { name born } }' });
console.log(JSON.stringify(result.data));field: author
return type: Author
operation: query AuthorCard
client selected: name, born
{"author":{"name":"Chimamanda Ngozi Adichie","born":1977}}
Arguments vs context: which one?
- Use arguments for things the client legitimately chooses: filters, ids, page sizes, currencies.
- Use context for things the client must not control: who they are, their permissions, your infrastructure.
A schema like orders(userId: ID!) that trusts the client to say who they are is a security hole; myOrders (reading the user from the context) is not.
Test yourself
Which graphql-js option passes the per-request context?
rootValuecontextValuevariableValuesfieldResolver
Where should the authenticated user's identity come from?
- A
userIdargument chosen by the client - The context, built by the server from the request
- A global variable
- The root value
What is a typical use of the info argument?
- Reading the logged-in user
- Inspecting the field name, path and selected sub-fields
- Changing the schema
- Sending the HTTP response