0
0
GraphqlHow-ToBeginner · 4 min read

How to Use Apollo Link for GraphQL Requests

Use Apollo Link to customize the flow of GraphQL requests in Apollo Client by composing middleware and afterware. Create links like HttpLink for network requests and combine them with ApolloLink.from() to add features such as authentication or error handling.
📐

Syntax

Apollo Link is a chain of functions that control how GraphQL requests are sent and received. You create links like HttpLink for sending requests, and combine multiple links using ApolloLink.from(). Each link can modify requests or responses.

  • HttpLink: Sends GraphQL operations over HTTP.
  • ApolloLink.from([link1, link2]): Combines multiple links into one.
  • setContext(): Middleware to modify request context, e.g., add headers.
javascript
import { ApolloClient, InMemoryCache, ApolloLink, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const httpLink = new HttpLink({ uri: 'https://example.com/graphql' });

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: 'Bearer YOUR_TOKEN',
    }
  };
});

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

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

Example

This example shows how to create an Apollo Client with an authentication link that adds a token to headers, combined with an HTTP link that sends requests to a GraphQL server.

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

// HTTP link to GraphQL endpoint
const httpLink = new HttpLink({ uri: 'https://countries.trevorblades.com/' });

// Middleware to add auth token
const authLink = setContext((_, { headers }) => {
  const token = 'my-secret-token';
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  };
});

// Combine links
const link = ApolloLink.from([authLink, httpLink]);

// Create Apollo Client
const client = new ApolloClient({
  link: link,
  cache: new InMemoryCache()
});

// Sample query
const QUERY = gql`
  query GetCountry {
    country(code: "US") {
      name
      capital
      currency
    }
  }
`;

// Run query
client.query({ query: QUERY }).then(result => {
  console.log(result.data);
});
Output
{ country: { name: "United States", capital: "Washington D.C.", currency: "USD" } }
⚠️

Common Pitfalls

Common mistakes when using Apollo Link include:

  • Not combining links properly with ApolloLink.from(), causing middleware to be skipped.
  • Forgetting to return the modified context in setContext(), so headers are not added.
  • Placing HttpLink before middleware links, which prevents middleware from running.
  • Not handling errors in links, which can cause silent failures.

Always ensure middleware links come before HttpLink in the chain.

javascript
/* Wrong order - HttpLink before authLink, authLink won't run */
const wrongLink = ApolloLink.from([httpLink, authLink]);

/* Correct order - authLink before HttpLink */
const correctLink = ApolloLink.from([authLink, httpLink]);
📊

Quick Reference

ConceptDescription
HttpLinkSends GraphQL requests over HTTP.
setContextMiddleware to modify request headers or context.
ApolloLink.fromCombines multiple links into one chain.
Order of LinksMiddleware links must come before HttpLink.
Error HandlingUse error link to catch and handle errors.

Key Takeaways

Apollo Link lets you customize GraphQL request flow by chaining middleware and network links.
Always combine links with ApolloLink.from() and place middleware before HttpLink.
Use setContext() to add headers like authentication tokens to requests.
Test your link chain to ensure all middleware runs as expected.
Handle errors explicitly using error links to avoid silent failures.