The context argument helps share common data or tools across all parts of a GraphQL request. It makes it easy to access things like user info or database connections without repeating code.
0
0
Context argument in GraphQL
Introduction
When you want to check who is making a request to control access.
When you need to share a database connection with all resolvers.
When you want to pass user settings or preferences to many parts of your API.
When you want to log or track requests in one place.
When you want to share helper functions or services across resolvers.
Syntax
GraphQL
const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { // create and return context object return { user: getUserFromReq(req), db }; } });
The context function runs once per request and returns an object.
Resolvers receive this context as their third argument.
Examples
Simple context returning a database connection.
GraphQL
context: () => ({ db: myDatabase })Context that extracts user info from request headers.
GraphQL
context: ({ req }) => {
const user = authenticate(req.headers.authorization);
return { user };
}Context with user info and helper functions.
GraphQL
context: ({ req }) => {
return {
user: getUser(req),
helpers: { formatDate, calculateAge }
};
}Sample Program
This example shows how the context argument passes user info to resolvers. The resolver returns the user's name if logged in, or 'Guest' otherwise.
GraphQL
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 === 'token123') { 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: 'token123' } }; server.executeOperation({ query: '{ currentUserName }' }, { req: fakeReq }).then(response => { console.log(response.data); });
OutputSuccess
Important Notes
Context is created fresh for each request to avoid sharing data between users.
Use context to keep your resolvers clean and focused on data fetching.
Summary
The context argument shares common data for all resolvers during a request.
It is useful for authentication, database access, and shared helpers.
Resolvers receive context as their third argument to use shared info easily.