Back to Apollo Client

Basic HTTP networking

docs/source/networking/basic-http-networking.mdx

3.14.13.2 KB
Original Source

Apollo Client has built-in support for communicating with a GraphQL server over HTTP with HttpLink. To set up this communication, provide an HttpLink instance as the link option to the ApolloClient constructor:

js
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: "https://api.example.com",
  }),
});

If you provide this parameter, Apollo Client sends all GraphQL operations (queries and mutations) to the specified URL over HTTP.

Including credentials in requests

HttpLink can include user credentials (basic auth, cookies, etc.) in the HTTP requests it makes to a GraphQL server. By default, credentials are included only if the server is hosted at the same origin as the application using Apollo Client. You can adjust this behavior by providing a value for the credentials option to the HttpLink constructor:

js
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: "https://api.example.com",
    // Enable sending cookies over cross-origin requests
    credentials: "include",
  }),
});

The following values for credentials are supported:

OptionDescription
same-originSend user credentials (cookies, basic http auth, etc.) if the server's URL is on the same origin as the requesting client. This is the default value.
omitNever send or receive credentials.
includeAlways send user credentials (cookies, basic http auth, etc.), even for cross-origin requests.

For more information, see Request.credentials.

Customizing request headers

You can specify the names and values of custom headers to include in every HTTP request to a GraphQL server. To do so, provide the headers option to the HttpLink constructor, like so:

js
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: "https://api.example.com",
    headers: {
      authorization: localStorage.getItem("token"),
      "client-name": "WidgetX Ecom [web]",
      "client-version": "1.0.0",
    },
  }),
});

API

<InterfaceDetails headingLevel={3} canonicalReference="@apollo/client!HttpLink.Options:interface" displayName="HttpLink.Options" customPropertyOrder={["uri", "credentials", "headers", "http"]} />

<InterfaceDetails headingLevel={3} canonicalReference="@apollo/client!HttpLink.ContextOptions:interface" displayName="HttpLink.ContextOptions" />