docs/source/api/link/apollo-link-context.mdx
<DocBlock canonicalReference="@apollo/client/link/context!SetContextLink:class" customOrder={["summary", "remarks", "example"]} />
constructor(
setter: SetContextLink.ContextSetter
): SetContextLink
The most common use case is adding authentication headers to requests:
const authLink = new SetContextLink((prevContext, operation) => {
const token = getAuthToken();
return {
headers: {
...prevContext.headers,
authorization: token ? `Bearer ${token}` : "",
},
};
});
You can also perform asynchronous operations to fetch tokens or other data:
const asyncAuthLink = new SetContextLink(async (prevContext, operation) => {
const token = await fetchAuthToken();
return {
headers: {
...prevContext.headers,
authorization: `Bearer ${token}`,
},
};
});
Typically async actions can be expensive and may not need to be called for every request, especially when a lot of request are happening at once. You can setup your own caching and invalidation outside of the link, to make it faster but still flexible.
Take for example a user auth token being found, cached, then removed on a 401 response:
import { ServerError } from "@apollo/client";
import { SetContextLink } from "@apollo/client/link/context";
import { ErrorLink } from "@apollo/client/link/error";
// cached storage for the user token
let token;
const withToken = new SetContextLink(async (prevContext, operation) => {
// if you have a cached value, return it immediately
if (token) {
return {
headers: {
...prevContext.headers,
authorization: `Bearer ${token}`,
},
};
}
const userToken = await AsyncTokenLookup();
token = userToken;
return {
headers: {
...prevContext.headers,
authorization: `Bearer ${token}`,
},
};
});
const resetToken = new ErrorLink(({ error }) => {
if (ServerError.is(error) && error.statusCode === 401) {
// remove cached token on 401 from the server
token = null;
}
});
const authFlowLink = withToken.concat(resetToken);
<FunctionDetails canonicalReference="@apollo/client/link/context!SetContextLink.SetContextLinkDocumentationTypes.ContextSetter:function(1)" headingLevel={3} result={false} displayName="SetContextLink.ContextSetter" />
SetContextLink.SetContextOperationtype SetContextOperation = Omit<
ApolloLink.Operation,
"getContext" | "setContext"
>;