Apollo HTTP Link

1.5.17 · maintenance · verified Tue Apr 21

apollo-link-http is a foundational, terminating link within the Apollo Link ecosystem, designed to transport GraphQL queries, mutations, and subscriptions over standard HTTP. It serves as the primary method for connecting an Apollo Client instance to a GraphQL server via fetch. Currently at version 1.5.17, this package is considered stable but is part of the older `apollo-link` architecture, which has largely been superseded by integrated link implementations within `@apollo/client` v3 and newer. It supports both POST and GET requests and offers extensive options for dynamic URIs, custom headers, credentials, and fetch behavior, including per-query overrides via context. Its key differentiator is its modularity within the `apollo-link` chain, allowing it to be composed with other links for features like error handling, retries, or batching. It requires a `fetch` compatible API in the runtime environment.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing `apollo-link-http` and integrating it with Apollo Client, including dynamic headers.

import { ApolloClient, InMemoryCache } from '@apollo/client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from '@apollo/client/link/context';

// Configure the HTTP link
const httpLink = createHttpLink({
  uri: process.env.GRAPHQL_URI ?? '/graphql',
});

// Optionally, add an auth link to set headers dynamically
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

// Initialize Apollo Client with the composed link and a cache
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

// Example query using the client (requires @apollo/client to be installed)
// import { gql } from '@apollo/client';
// client.query({
//   query: gql`
//     query GetDogs {
//       dogs {
//         id
//         breed
//       }
//     }
//   `
// }).then(result => console.log(result.data));

view raw JSON →