Skip to content

The GraphQL Client: Apollo Link and Fragments

Apollo Link runs every GraphQL operation through a chain of middleware: authLink sets headers, errorLink handles errors in one place, split routes subscriptions. Plus fragments as reusable field sets and why interfaces need possibleTypes.

≈ 15 min readSoftwareGraphQLAPI

The post on Apollo Client caching was about what happens to a response once it reaches the client: how the normalized cache breaks the data apart, stores it and finds it again. This time I turn the view around. Before a response can land in the cache, the request has to go out to the server, and along the way there are decisions that have nothing to do with the individual query: sending a token, handling a 401 in one place, routing subscriptions to a different transport. These are cross-cutting concerns, and the real question is not which API you call for them but where they belong. Spread across every single useQuery call, or bundled in one place.

That is exactly the decision this post is about, and I consider the bundled variant the more sustainable one. Apollo Client answers it with a chain of middleware. The trade-off is manageable: you accept one indirection that you have to understand once, and you get an architecture in which auth, error handling and routing each live in one named place instead of being scattered across dozens. If the auth strategy changes, you change one link, not forty components. That is how you measure the value of a transport layer, not by the number of its options.

Requirements like these arrive in stages. First there is an ApolloClient, and everything works. Then someone says: “We need to send an auth token.” Shortly after: “And when the server returns a 401, all affected operations should be handled centrally.” And finally: “Oh, and we need subscriptions too.” By this point at the latest, it becomes clear that the one network link from the setup was only the tip. Underneath sits a composable system built for exactly these cases: Apollo Link.

The second part of this post is about fragments. At first glance they look like a mere convenience for writing, but they are the building block that lets you compose queries cleanly and keep components maintainable. I use Apollo Client 3.10; the import paths and signatures refer to this version. In Apollo Client 4, React hooks such as useFragment come from @apollo/client/react; the cache model shown here stays the same.

The basic idea is quickly told. Every operation, whether query, mutation or subscription, passes through a chain of links before it reaches the server, and the response travels back through the same chain in reverse. A link is a piece of middleware: it may look at the operation, change it and pass it on to the next link. The last link in the chain is special. It is terminating, which means it does not pass anything on but actually sends the request. In the vast majority of cases, that is the HttpLink.

If you have ever seen Express middleware or a Redux middleware chain, you will recognize the pattern right away. Each link receives the operation and a forward function it uses to hand over to the next link. And as with any middleware chain, the order determines the behavior.

You assemble the chain with ApolloLink.from, which links an array of links in exactly the order in which they appear. For two links, linkA.concat(linkB) is enough. Let’s look at a typical chain.

import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';

const httpLink = new HttpLink({ uri: '/graphql' });

const authLink = setContext((_, { headers }) => {
  const token = getToken();
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
  if (graphQLErrors) {
    for (const err of graphQLErrors) {
      console.error(`[GraphQL error] ${operation.operationName}: ${err.message}`);
    }
  }
  if (networkError) {
    console.error(`[Network error] ${networkError.message}`);
  }
});

const link = ApolloLink.from([errorLink, authLink, httpLink]);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

Three links, a clear division of labor. The errorLink sits on the outside because it should see both the outgoing operation and the incoming response. Errors that occur deep in the chain pass through it on the way back. The authLink sits just before the network link because it sets the token as late as possible, when it is most current. And the httpLink sits at the very end because it is terminating.

Why the order matters#

This is exactly where the pitfall lies that I run into most often in code reviews. The terminating link has to be the last element. If the authLink accidentally sits behind the httpLink, it is never reached, because the request has long been sent by the time this link would get its turn. The result: the token is missing, the server responds with 401, and debugging starts in completely the wrong place, at the auth server instead of the link order.

The authLink deserves a second look because its name can be misleading. setContext does not change the HTTP headers directly. It returns an object that is merged into the operation’s context, usually under the key headers. Only the HttpLink reads this context and translates it into real HTTP headers. So the authLink only prepares; the sending happens elsewhere. Once you have internalized that, you also understand why the order is so important: the preparer has to come before the sender.

A detail you need often in practice: the function in setContext may be asynchronous. If it returns a promise, Apollo Link waits before the operation continues. That lets you load or refresh a token on demand without burdening the calling component with it. Just keep in mind that every operation waits for this resolution: a slow token endpoint then slows down all requests. As a rule, you therefore keep the token in a store that setContext can read synchronously and trigger the refresh separately.

The errorLink distinguishes two classes of errors that you should not confuse. graphQLErrors is an array of errors the server returned deliberately, such as a failed validation or a record that was not found. The transport worked; the response simply contains errors in the errors field. networkError, on the other hand, means that the transport itself failed: no connection, a 500, a timeout. This separation is why onError is the right place for central handling. You do not have to check in every single useQuery call whether the token has expired; you do it once, in one place.

When I draw the same chain as a diagram, the path of an operation looks like this.

flowchart LR
  Op[Operation] --> E[errorLink onError]
  E --> A[authLink setContext]
  A --> H[httpLink terminating]
  H --> S[(GraphQL Server)]
  S -. response .-> H
  H -. response .-> A
  A -. response .-> E
  E -. response .-> Op

The solid arrows show the request going out, the dashed ones the response on the way back. The fact that the errorLink takes part in both directions makes clear why it sits on the very outside.

Beyond the three mentioned, there are a few links you need regularly. Here are the most important ones with their respective jobs:

  • errorLink (onError): central handling of GraphQL and network errors, such as logging or logging out when a token has expired.
  • authLink (setContext): prepares headers and token and merges them into the operation context.
  • retryLink (RetryLink): retries operations on network errors, with configurable backoff and jitter.
  • splitLink (split): routes operations to different branches based on a predicate, classically subscriptions versus queries.
  • httpLink (HttpLink): the terminating link that sends the request over HTTP.

The RetryLink belongs in the chain before the terminating link so that it can trigger the retry before the request finally goes out. A sensible complete chain would therefore be from([errorLink, retryLink, authLink, httpLink]). One important point: set the retry condition explicitly. If you unconditionally return a forward(operation) in onError to retry an operation, this can turn into an infinite loop when the error is permanent. The RetryLink with its retryIf condition is the more robust way because it limits the number of attempts.

import { RetryLink } from '@apollo/client/link/retry';

const retryLink = new RetryLink({
  delay: { initial: 300, max: 3000, jitter: true },
  attempts: {
    max: 3,
    retryIf: (error) => Boolean(error),
  },
});

Branching off subscriptions with split#

As soon as subscriptions come into play, a second transport may become necessary. In this example, queries and mutations run over HTTP, subscriptions over a persistent WebSocket connection. Other stacks transport subscriptions over HTTP and server-sent events. In the WebSocket setup shown here, split takes on the job of directing the operation to the right branch. The function receives a predicate and two links: if the predicate is true, the operation goes into the first branch, otherwise into the second.

To decide whether an operation is a subscription, getMainDefinition helps. It extracts the main definition from the query document so that you can check kind and operation.

import { split } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';

const wsLink = new GraphQLWsLink(
  createClient({ url: 'wss://example.com/graphql' }),
);

const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  ApolloLink.from([errorLink, authLink, httpLink]),
);

The WebSocket transport here is called GraphQLWsLink and builds on the graphql-ws library. For a WebSocket branch, that is the right choice. The older combination of WebSocketLink and subscriptions-transport-ws still shows up in many projects, but it is considered deprecated. Whether WebSocket is the right transport at all depends on the server and the subscription protocol in use; SSE is one possible alternative.

One point that is easy to overlook: the WebSocket branch bypasses errorLink and authLink because it hangs off its own branch in split. A subscription therefore does not authenticate via the HTTP header but via the connectionParams of the graphql-ws client, which are set when the connection is established. If you only pass the token in the authLink, you will otherwise wonder why the query is authorized but the subscription is not.

From Apollo detail to principle#

Take a step back, and it is no longer about Apollo. The link chain is a special case of a pattern that reaches far beyond GraphQL: cross-cutting concerns move out of the domain code into a chain of middleware that every operation passes through. Auth, logging, error handling, retries, routing. These are concerns that are needed everywhere and belong nowhere in the domain. Express does it with its middleware, Redux with its middleware chain, an API gateway with its filter chain, and Apollo Client with its links. Once you have recognized the pattern, you see it everywhere.

The appeal lies in drawing a clear line. Domain code requests data and displays it. It should know nothing about how a token comes about or what happens on a 401. The chain takes this off its hands, and it does so in a single, named place. The gain is not the technique but the locality of change. A new concern arrives as an additional link without touching a single useQuery call. That is the difference between an adjustment you finish in an afternoon and one that runs through forty files and carries a risk in each of them.

This does not come for free. The price is indirection. The path of an operation no longer reads linearly in the component code but is spread across a chain whose order you have to know to understand the behavior. A misplaced link is harder to find than a wrongly set header right at the call site. For a handful of operations without shared concerns, the chain would therefore be effort without return.

The assignment comes down to a few criteria. If a concern affects many or all operations, it belongs in the chain. If it affects exactly one, it belongs at the call site. If it changes independently of the domain code and for different reasons, that is a strong signal for the chain. And the more such concerns are on the table at the same time, the more clearly the separation pays off, because it prevents auth, errors and transport from getting mixed up in the same piece of code. In exactly this situation, when several concerns come together, the chain is not overhead but what keeps the codebase clear.

Fragments: queries from building blocks#

On to the second half. A fragment is a named, reusable set of fields of a specific type. Instead of listing the same fields again in every query that loads a User, you define them once and insert them with a spread.

import { gql } from '@apollo/client';

const USER_FIELDS = gql`
  fragment UserFields on User {
    id
    name
    email
  }
`;

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      ...UserFields
    }
  }
  ${USER_FIELDS}
`;

Two things matter. The spread ...UserFields refers to the fragment, and the fragment document has to be passed to the query via ${USER_FIELDS}, otherwise the parser does not know the name. This is a common beginner’s mistake: the spread is there, but the interpolation is missing, and the error message is not particularly telling.

The real gain only shows in a larger project, and it is called colocation. The idea: a fragment sits right next to the component that displays exactly these fields. A UserCard component defines its own UserFields fragment and exports it. The parent query that fills several components collects the fragments of its children and puts them together. If the fields the UserCard needs change, only its fragment changes, and the query at the top picks up the change automatically. The data requirement lives where the data is needed, not in a distant, central query file that nobody wants to maintain anymore.

Since Apollo Client 3.8 there is also the hook useFragment for this. It lets a component read exactly the fields of a fragment from the cache without issuing a query itself. The component only re-renders when the fields of its fragment change, a finer cut than re-rendering on every change to the parent query.

import { useFragment } from '@apollo/client';

function UserCard({ id }: { id: string }) {
  const { data } = useFragment({
    fragment: USER_FIELDS,
    fragmentName: 'UserFields',
    from: { __typename: 'User', id },
  });

  return <div>{data.name} · {data.email}</div>;
}

Fragment matching and possibleTypes#

One last point that is often overlooked and then causes errors that are hard to track down. As soon as a fragment sits on an interface or a union instead of a concrete type, the cache has to know which concrete types belong to this abstract type. Take an interface SearchResult that is implemented by User and Post. A query wants to load different fields depending on the concrete type.

query Search($term: String!) {
  search(term: $term) {
    __typename
    ... on User {
      name
    }
    ... on Post {
      title
    }
  }
}

For Apollo to match these inline fragments, ... on User and ... on Post, correctly, the InMemoryCache needs a possibleTypes entry. It tells the cache which concrete types stand behind each interface or union.

const cache = new InMemoryCache({
  possibleTypes: {
    SearchResult: ['User', 'Post'],
  },
});

Without this entry, the cache cannot perform the matching reliably. Fields are then missing from the results, or Apollo falls back on a heuristic and prints a warning. The tricky part is that it seems to work anyway in simple cases and only breaks with more complex queries. That is why you are best off not maintaining possibleTypes by hand at all but generating it from the schema, via introspection or with GraphQL Codegen. That way the entry stays up to date automatically when a new type implements the interface.

Conclusion#

The transport layer of Apollo Client is not a monolithic network component but a chain of small, clearly defined pieces. The return only shows in the effect. Because every concern sits in exactly one place, later adjustments are local instead of scattered. That shortens cycles, reduces friction with every change to auth or error handling and keeps the boundary between domain code and infrastructure clean. The price is the indirection of the chain, and most of the frustrating debugging sessions I have experienced with it come down to a swapped order. That is a fair deal as long as you set the order deliberately and put the terminating HttpLink at the end.

Fragments are the counterpart on the query side and follow the same principle. They keep field sets reusable and enable colocation close to the components, so that the data requirement lives where the data is needed and not in one giant central query that nobody wants to maintain anymore. When a component changes its needs, its fragment changes instead of a distant file. As soon as abstract types come into play, possibleTypes is the easily forgotten prerequisite without which matching breaks. Link order and fragment boundaries thus remain two concrete places where I review changes; Apollo does not make these decisions for me.

How the token that the authLink sets comes about in the first place and how it is checked on the server is a topic of its own; the post on GraphQL auth in the context fits here. And when the loaded lists grow, it is worth looking at GraphQL pagination and connections, where fragments and fetchMore work together.

Further reading#

Revised and translated from German with the help of AI.