Back to Apollo Client

SetContextLink

docs/source/api/link/apollo-link-context.mdx

3.14.12.6 KB
Original Source

<DocBlock canonicalReference="@apollo/client/link/context!SetContextLink:class" customOrder={["summary", "remarks", "example"]} />

Constructor signature

ts
constructor(
  setter: SetContextLink.ContextSetter
): SetContextLink

Usage examples

Authentication

The most common use case is adding authentication headers to requests:

ts
const authLink = new SetContextLink((prevContext, operation) => {
  const token = getAuthToken();

  return {
    headers: {
      ...prevContext.headers,
      authorization: token ? `Bearer ${token}` : "",
    },
  };
});

Asynchronous token lookup

You can also perform asynchronous operations to fetch tokens or other data:

ts
const asyncAuthLink = new SetContextLink(async (prevContext, operation) => {
  const token = await fetchAuthToken();

  return {
    headers: {
      ...prevContext.headers,
      authorization: `Bearer ${token}`,
    },
  };
});

Caching lookups

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:

js
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);

Types

<FunctionDetails canonicalReference="@apollo/client/link/context!SetContextLink.SetContextLinkDocumentationTypes.ContextSetter:function(1)" headingLevel={3} result={false} displayName="SetContextLink.ContextSetter" />

<DocBlock canonicalReference="@apollo/client/link/context!SetContextLink.SetContextOperation:type" />

Signature

ts
type SetContextOperation = Omit<
  ApolloLink.Operation,
  "getContext" | "setContext"
>;