Context and resolver arguments
Every resolver receives parent, args, context and info. Build context once per request for the database and current user, and learn what info is for.
Context and resolver arguments
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A resolver receives four arguments: `parent` (the value the previous resolver returned), `args` (this field's arguments), `context` (shared by every resolver in the request) and `info` (details about the field and the operation).
- The context factory runs once per request, and every resolver in that request sees the same object; it is the place for the database handle, the current user and per-request caches.
- Do not import the database or read the user from a global in each resolver; take them from context, so tests can pass fakes and each request carries its own identity.
- Authentication belongs in the context factory, which turns a header into a user; authorization belongs in resolvers or the services they call.
- `info` exposes the field name, parent type, return type and path; reach for it only for generic tooling, not for everyday resolvers.
The problem: resolvers need things that are not in the query
A resolver for Query.post needs a database. A resolver for Mutation.deletePost needs to know who is calling. Neither is a GraphQL argument. If every resolver imports a global db and reads a global currentUser, tests become awkward and, worse, two simultaneous requests can see each other’s identity.
GraphQL answers with a fixed signature. Every resolver gets the same four arguments:
function resolver(parent, args, context, info) { /* ... */ }
The four arguments
parent is the object the previous resolver returned. Post.author gets the post row. For fields on the root Query, there is no real parent, so people write _.
args is an object of the field’s arguments with defaults applied. For post(id: ID!) it is { id: "3" }. The server has already validated types, so args.id is a string, not something that might be an array.
context is the one you control. It is created once per request and handed to every resolver in that request.
info describes the execution: the field name, the parent type, the return type, the path from the root, the whole parsed document. You rarely need it in app code. Tools that wrap resolvers, such as logging or caching layers, use it constantly.
I recorded what a root resolver saw for { post(id: "3") { ... } } with the header x-user: ada:
parent=undefined
args={ id: "3" }, context has db: true, context.user: "ada"
info.fieldName = "post", info.parentType.name = "Query"
Building context
In Yoga the context factory takes the request and returns an object:
const yoga = createYoga({
schema,
context: async ({ request }) => {
const token = request.headers.get('authorization')?.replace('Bearer ', '');
return {
db,
user: await userFromToken(token), // null when anonymous
};
},
});
Here is a test I ran, with a context that builds a fake user from the token and gives each request a random id:
{ me a b whereAmI } with "Bearer t1"
-> { me: "ada", a: "a", b: "b", whereAmI: "Query.whereAmI -> returns String!" }
context built 1 time(s); distinct requestIds seen by a and b: 1
One request, one context, shared by all resolvers. Think of it as the tray a waiter carries to the table: everyone at the table uses the same salt and pepper, but the next table gets its own.
Authenticate in context, authorize in resolvers
The factory answers “who is this?” and nothing more. It should not reject the request, because many fields are public. Put the check where the sensitive data is:
secret: (_parent, _args, { user }) => {
if (!user.isAdmin) {
throw new GraphQLError('Not allowed', { extensions: { code: 'FORBIDDEN' } });
}
return 's3cret';
},
With a non-admin token on { me secret } I got {"errors":[{"message":"Not allowed","path":["secret"],"extensions":{"code":"FORBIDDEN"}}],"data":null}. The data is null because secret is declared String! and non-null violations spread to the parent, here the root; with a nullable secret, me would still have returned. That behavior is in nullability in practice.
Keep the check close to the data, not only at the edge: the same record can be reached through many paths, such as Query.post, Author.posts or a search result, and each path must apply the rule. Putting it in a service function that every resolver calls is more reliable than remembering it in each resolver.
Context is where per-request state lives
Because context lives for exactly one request, it is the right home for anything that must not leak across requests. The most important example is a DataLoader, which caches results and has to start empty for each request. A module-level DataLoader would hand one user’s cached rows to another.
Other residents: a logger tagged with a request id, a transaction handle, feature flags resolved for this user.
What the video covers
The embedded clip is Warren Day’s chapter “Part 9: Server Context” from his 2025 full GraphQL course, 28:32 to 34:06 of a 4 hour 20 minute video. The chapter is placed between server setup and implementing the schema. From the chapter list alone, it adds a context to the server; I could not read a transcript, and the course may use a different server library from Yoga, so treat the code above as this lesson’s reference. Jamie Barton’s two-minute context video, listed below, shows sharing database connections and DataLoaders through context.
Where this fits
Resolvers now have what they need: parent, arguments, a shared database and an identity. Before wiring up a database, there is a choice about how the schema itself gets written. Next: schema-first and code-first.
Check yourself
What are the four resolver arguments, in order?
`parent`, `args`, `context` and `info`. In a root resolver `parent` is the root value, which is usually unused.
Why put the current user on the context instead of reading it in each resolver?
The context factory resolves the user from the request once, and all resolvers share it. It also keeps resolvers testable, because a test passes its own context.
How many times is the context factory called for `{ me a b }`?
Once. The three resolvers see the same context object, which I confirmed by checking that they all read the same per-request id.
Is a failed login a context error or a resolver error?
Usually neither. The factory can return an anonymous user, and the resolvers that need a login throw a `FORBIDDEN` or `UNAUTHENTICATED` error, so public fields keep working.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.