Apollo HTTP Link
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
-
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.fixInstall 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: Network error: Failed to fetch
cause Generic network error often due to incorrect URI, server being down, CORS issues, or firewall blocking the request.fixVerify 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. -
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.fixEnsure 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.
Warnings
- 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.
- 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.
- 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.
- 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.
Install
-
npm install apollo-link-http -
yarn add apollo-link-http -
pnpm add apollo-link-http
Imports
- createHttpLink
const { createHttpLink } = require('apollo-link-http');import { createHttpLink } from 'apollo-link-http'; - HttpLink
import { HttpLink } from 'apollo-link-http';
Quickstart
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));