HTTP Link
Get GraphQL results over a network using HTTP fetch.
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:
import { HttpLink } from '@apollo/client';const link = new HttpLink({uri: "http://localhost:4000/graphql"// Additional options});
HttpLink
constructor options
HttpLink
constructor optionsThe 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
Name / Type | Description |
---|---|
uri
| The URL of the GraphQL endpoint to send requests to. Can also be a function that accepts an The default value is |
includeExtensions
| If true, includes the The default value is |
fetch
| A function to use instead of calling the By default, the Fetch API is used unless it isn't available in your runtime environment. See |
headers
| An object representing headers to include in every HTTP request, such as |
preserveHeaderCase
| 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 |
credentials
| The credentials policy to use for each |
fetchOptions
| An object containing options to use for each call to Note that if you set |
useGETForQueries
| If The default value is |
print
| An optional function to use when transforming a query or mutation
By default the bare |
Context options
HttpLink
checks the context
HttpLink
for each operation.
Some of these values can also be provided as options to HttpLink
constructorcontext
takes precedence.
Name / Type | Description |
---|---|
uri
| The URL of the GraphQL endpoint to send requests to. Can also be a function that accepts an The default value is |
headers
| An object representing headers to include in the HTTP request, such as |
credentials
| The credentials policy to use for this |
fetchOptions
| An object containing options to use for this call to Note that if you set |
http
| An object that configures advanced |
http
option fields
http
option fieldsName / Type | Description |
---|---|
includeExtensions
| If true, includes the The default value is |
includeQuery
| If The default value is |
preserveHeaderCase
| 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 |
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
The following types of errors can occur:
Error | Description | Callback | Error Type |
---|---|---|---|
Client Parse | The request body is not serializable, for example due to a circular reference. | error | ClientParseError |
Server Parse | The server's response cannot be parsed ( response.json() ) | error | ServerParseError |
Server Network | The server responded with a non-2xx HTTP code. | error | ServerError |
Server Data | The server's response didn't contain data or errors . | error | ServerError |
GraphQL Error | Resolving the GraphQL operation resulted in at least one error, which is present in the errors field. | next | Object |
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
//type ClientParseError{parseError: Error; // Error returned from response.json()};//type ServerParseError{response: Response; // Object returned from fetch()statusCode: number; // HTTP status codebodyText: string // text that was returned from server};//type ServerError{result: Record<string, any>; // Parsed object from server responseresponse: Response; // Object returned from fetch()statusCode: number; // HTTP status code};
Customizing fetch
fetch
You can provide the fetch
optionHttpLink
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
. We recommend unfetch
node-fetch
Custom auth
This example adds a custom Authorization
header to every request before calling fetch
:
const customFetch = (uri, options) => {const { header } = Hawk.client.header("http://example.com:8000/resource/1?b=1&a=2","POST",{ credentials: credentials, ext: "some-app-data" });options.headers.Authorization = header;return fetch(uri, options);};const link = new HttpLink({ fetch: customFetch });
Dynamic URI
This example customizes the endpoint URL's query parameters before calling fetch
:
const customFetch = (uri, options) => {const { operationName } = JSON.parse(options.body);return fetch(`${uri}/graph/graphql?opname=${operationName}`, options);};const link = new HttpLink({ fetch: customFetch });