HTTP Link

Get GraphQL results over a network using HTTP fetch.


We recommend reading Apollo Link overview before learning about individual links.

HttpLink is a terminating link that sends a GraphQL operation to a remote endpoint over HTTP. Apollo Client uses HttpLink by default when you provide the uri option to the ApolloClient constructor.

HttpLink supports both POST and GET requests, and you can configure HTTP options on a per-operation basis. You can use these options for authentication, persisted queries, dynamic URIs, and other granular updates.

Usage

Import the HttpLink class and initialize a link like so:

JavaScript
1import { HttpLink } from '@apollo/client';
2
3const link = new HttpLink({
4  uri: "http://localhost:4000/graphql"
5  // Additional options
6});

The HttpLink constructor takes an options object that can include the fields below. Note that you can also override some of these options on a per-operation basis using the operation context.

Name /
Type
Description
uri

String or Function

The URL of the GraphQL endpoint to send requests to. Can also be a function that accepts an Operation object and returns the string URL to use for that operation.

The default value is /graphql.

includeExtensions

Boolean

If true, includes the extensions field in operations sent to your GraphQL endpoint.

The default value is false.

fetch

Function

A function to use instead of calling the Fetch API directly when sending HTTP requests to your GraphQL endpoint. The function must conform to the signature of fetch.

By default, the Fetch API is used unless it isn't available in your runtime environment.

See Customizing fetch.

headers

Object

An object representing headers to include in every HTTP request, such as {Authorization: 'Bearer abc123'}.

preserveHeaderCase

Boolean

If set to true, header names won't be automatically normalized to lowercase. This allows for non-http-spec-compliant servers that might expect capitalized header names.

The default value is false.

credentials

String

The credentials policy to use for each fetch call. Can be omit, include, or same-origin.

fetchOptions

Object

An object containing options to use for each call to fetch. If a particular option is not included in this object, the default value of that option is used.

Note that if you set fetchOptions.method to GET, HttpLink follows standard GraphQL HTTP GET encoding.

See available options

useGETForQueries

Boolean

If true, the link uses an HTTP GET request when sending query operations to your GraphQL endpoint. Mutation operations continue to use POST requests. If you want all operations to use GET requests, set fetchOptions.method instead.

The default value is false.

print

Function

An optional function to use when transforming a query or mutation DocumentNode into a string. It accepts an ASTNode (typically a DocumentNode) and the original print function as arguments, and is expected to return a string. This option can be used with stripIgnoredCharacters to remove whitespace from queries.

JavaScript
1import { stripIgnoredCharacters } from 'graphql';
2
3const httpLink = new HttpLink({
4  uri: '/graphql',
5  print: (ast, originalPrint) => stripIgnoredCharacters(originalPrint(ast)),
6});

By default the bare GraphQL print function is used.

Context options

HttpLink checks the current operation's context for certain values before sending its request to your GraphQL endpoint. Previous links in the link chain can set these values to customize the behavior of HttpLink for each operation.

Some of these values can also be provided as options to the HttpLink constructor. If a value is provided to both, the value in the context takes precedence.

Name /
Type
Description
uri

String or Function

The URL of the GraphQL endpoint to send requests to. Can also be a function that accepts an Operation object and returns the string URL to use for that operation.

The default value is /graphql.

headers

Object

An object representing headers to include in the HTTP request, such as {Authorization: 'Bearer abc123'}.

credentials

String

The credentials policy to use for this fetch call. Can be omit, include, or same-origin.

fetchOptions

Object

An object containing options to use for this call to fetch. If a particular option is not included in this object, the default value of that option is used.

Note that if you set fetchOptions.method to GET, HttpLink follows standard GraphQL HTTP GET encoding.

See available options

http

Object

An object that configures advanced HttpLink functionality, such as support for persisted queries. Options are listed in http option fields.

http option fields

Name /
Type
Description
includeExtensions

Boolean

If true, includes the extensions field in operations sent to your GraphQL endpoint.

The default value is false.

includeQuery

Boolean

If false, the GraphQL query string is not included in the request. Set this option if you're sending a request that uses a persisted query.

The default value is true.

preserveHeaderCase

Boolean

If set to true, header names won't be automatically normalized to lowercase. This allows for non-http-spec-compliant servers that might expect capitalized header names.

The default value is false.

Operation results

After your GraphQL endpoint (successfully) responds with the result of the sent operation, HttpLink sets it as the response field of the operation context. This enables each previous link in your link chain to interact with the response before it's returned.

Handling errors

HttpLink distinguishes between client errors, server errors, and GraphQL errors. You can add the onError link to your link chain to handle these errors via a callback.

The following types of errors can occur:

ErrorDescriptionCallbackError Type
Client ParseThe request body is not serializable, for example due to a circular reference.errorClientParseError
Server ParseThe server's response cannot be parsed (response.json())errorServerParseError
Server NetworkThe server responded with a non-2xx HTTP code.errorServerError
Server DataThe server's response didn't contain data or errors.errorServerError
GraphQL ErrorResolving the GraphQL operation resulted in at least one error, which is present in the errors field.nextObject

Because many server implementations can return a valid GraphQL result on a server network error, the thrown Error object contains the parsed server result. A server data error also receives the parsed result.

All error types inherit the name, message, and nullable stack properties from the generic javascript Error:

JavaScript
1//type ClientParseError
2{
3  parseError: Error;                // Error returned from response.json()
4};
5
6//type ServerParseError
7{
8  response: Response;               // Object returned from fetch()
9  statusCode: number;               // HTTP status code
10  bodyText: string                  // text that was returned from server
11};
12
13//type ServerError
14{
15  result: Record<string, any>;      // Parsed object from server response
16  response: Response;               // Object returned from fetch()
17  statusCode: number;               // HTTP status code
18};

Customizing fetch

You can provide the fetch option to the HttpLink constructor to enable many custom networking needs. For example, you can modify the request based on calculated headers or calculate the endpoint URI based on the operation's details.

If you're targeting an environment that doesn't provide the Fetch API (such as older browsers or the server) you can provide a different implementation of fetch. We recommend unfetch for older browsers and node-fetch for running in Node.

Custom auth

This example adds a custom Authorization header to every request before calling fetch:

JavaScript
1const customFetch = (uri, options) => {
2  const { header } = Hawk.client.header(
3    "http://example.com:8000/resource/1?b=1&a=2",
4    "POST",
5    { credentials: credentials, ext: "some-app-data" }
6  );
7  options.headers.Authorization = header;
8  return fetch(uri, options);
9};
10
11const link = new HttpLink({ fetch: customFetch });

Dynamic URI

This example customizes the endpoint URL's query parameters before calling fetch:

JavaScript
1const customFetch = (uri, options) => {
2  const { operationName } = JSON.parse(options.body);
3  return fetch(`${uri}/graph/graphql?opname=${operationName}`, options);
4};
5
6const link = new HttpLink({ fetch: customFetch });
Feedback

Edit on GitHub

Forums