Apollo HTTP Link

raw JSON →
1.5.17 verified Tue Apr 21 auth: no javascript maintenance

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.

error ReferenceError: fetch is not defined
cause The runtime environment (e.g., Node.js or older browser) does not natively support the `fetch` API, which `apollo-link-http` requires.
fix
Install and provide a fetch polyfill. For Node.js, install node-fetch (npm install node-fetch) and pass it to the link: import fetch from 'node-fetch'; const link = createHttpLink({ uri: '/graphql', fetch });.
error Error: Network error: Failed to fetch
cause Generic network error often due to incorrect URI, server being down, CORS issues, or firewall blocking the request.
fix
Verify the uri option points to a valid and accessible GraphQL endpoint. Check browser console for CORS errors. Ensure the GraphQL server is running and accessible from the client's network location. Temporarily disable security software if testing locally.
error GraphQL error: Must provide document
cause This error typically originates from the GraphQL server, indicating it received an empty or invalid GraphQL request, often a symptom of an issue with how the query or mutation is being sent by the client, or a malformed request body.
fix
Ensure that your ApolloClient instance is correctly configured with a cache and a link. Verify that the GraphQL query or mutation string is valid and being passed correctly to client.query() or client.mutate(). If using GET for queries, ensure the query parameters are not exceeding URL length limits.
breaking This package is part of the older `apollo-link` ecosystem. For new projects or when upgrading Apollo Client to v3 or higher, it is highly recommended to use the built-in HTTP link directly from `@apollo/client/link/http` instead of `apollo-link-http` to avoid potential compatibility issues and leverage modern features.
fix Migrate to `import { HttpLink } from '@apollo/client/link/http';` and instantiate using `new HttpLink({ uri: '/graphql' });`.
gotcha The `apollo-link-http` relies on a global `fetch` API. In environments like Node.js or older browsers that lack native `fetch`, you must provide a polyfill or custom `fetch` implementation via the `fetch` option during link creation.
fix For Node.js, use `node-fetch`: `import fetch from 'node-fetch'; const link = createHttpLink({ uri: '/graphql', fetch });`. For older browsers, use `unfetch` or a similar polyfill.
gotcha Setting `fetchOptions.method: 'GET'` on the link's options or via context will force *all* requests (queries and mutations) to use GET. To only use GET for queries while keeping mutations as POST, use the `useGETForQueries: true` option at the top level.
fix If only queries should use GET, set `createHttpLink({ uri: '/graphql', useGETForQueries: true })`. If all requests should be GET, `createHttpLink({ uri: '/graphql', fetchOptions: { method: 'GET' } })` is acceptable, but be aware of GraphQL HTTP GET specification limitations for complex queries.
gotcha Values provided in the `context` object (e.g., `context.headers`, `context.credentials`, `context.uri`, `context.fetchOptions`) will override any corresponding options initially set when creating the `HttpLink` instance. This is a powerful feature but can lead to unexpected behavior if not managed carefully, especially in multi-link chains.
fix Be explicit about where dynamic options are set. For per-request dynamic values, use `apollo-link-context` to merge or override options into the context before the HTTP link processes them. For global defaults, set them directly on `createHttpLink`.
npm install apollo-link-http
yarn add apollo-link-http
pnpm add apollo-link-http

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