Utility for setting context on Apollo Client GraphQL operations, enabling async lookups like authentication tokens. Current stable version is 1.0.20, with low release cadence (last update years ago). Part of the apollo-link chain ecosystem, it provides a simple imperative setContext function that returns either an object or a promise, allowing caching and conditional logic based on previous context. Key differentiator: handles asynchronous context preparation natively, unlike static context options.
npm install apollo-link-contextNo compatibility data collected yet for this library.
Verified import paths — ran on the pinned version, not inferred.
Creates an Apollo Link that sets an authorization header on every GraphQL request, preserving existing headers.
Upgrade to apollo-link-context@1.0.0+ or use @apollo/client/link/context for Apollo Client v3+.
Explicitly spread previousContext inside the setContext function to preserve fields.
Always return an object or a promise that resolves to an object from the setContext callback.
Migrate to Apollo Client v3's internal context link: import { setContext } from '@apollo/client/link/context';Wrap your static object in an arrow function: setContext(() => ({ token: 'abc' }))Use import { setContext } from 'apollo-link-context';Run npm install apollo-link-context or use the correct import from @apollo/client/link/context in Apollo Client v3+.
Provide default value for previousContext parameter: (_, { headers = {} } = {}) => ({ headers: { ...headers, Authorization: 'token' } })Ensure the promise resolves correctly and catch errors: setContext(() => fetchToken().catch(() => ({})))