Launch Apollo Studio

API Reference: @apollo/gateway

Apollo Gateway API reference


The core class of Apollo Server's federated gateway implementation. For an example of using ApolloGateway, see The gateway.

constructor(options): ApolloGateway


  • options: Object

    An object that contains configuration options for the gateway.

    Supported options include:

    • serviceList: ServiceDefinition[]

      Do not provide this option if you are using managed configuration. If you are not using managed configuration, this option is required.

      An array representing the implementing services that the gateway will use to resolve incoming GraphQL operations. Each object in the array specifies the name and url of an implementing service in your federated graph. You can specify any string value for the name field, which is used for identifying the service in log output and error messages, and for reporting metrics to Apollo Studio.

      const gateway = new ApolloGateway({
        serviceList: [    { name: 'products', url: 'https://products-service.dev/graphql' },    { name: 'reviews', url: 'https://reviews-service.dev/graphql' }  ]});
    • apq: Boolean

      When enabled the gateway will attempt to use automated persisted queries (APQ) when sending queries to downstream services. Depending on the complexity of queries sent to downstream services, this technique can greatly reduce the size of the payloads being transmitted over the network. Downstream implementing services must also support APQ functionality to participate in this feature (Apollo Server does by default unless it has been explicitly disabled). As with typical APQ behavior, a downstream server must have received and registered a query once before it will be able to serve an APQ request.

    • buildService: (service: ServiceDefinition) => GraphQLDataSource

      Define this function to customize your gateway's data transport to some or all of your data graph's implementing services. This customization can include using a protocol besides the default of HTTP.

      If you provide this function, ApolloGateway calls it for every implementing service in your data graph. The function must return an object that implements the GraphQLDataSource interface, such as an instance of RemoteGraphQLDataSource or a subclass of it.

      The example below demonstrates adding an x-user-id HTTP header to every request the gateway sends to an implementing service:

      class AuthenticatedDataSource extends RemoteGraphQLDataSource {  willSendRequest({ request, context }) {    request.http.headers.set('x-user-id', context.userId);  }}
      const gateway = new ApolloGateway({
        buildService({ name, url }) {    return new AuthenticatedDataSource({ url });  },});
    • introspectionHeaders: { [key: string]: string }

      An object containing HTTP headers that the gateway will include only when obtaining schema definitions from each of your implementing services.

      Note: If you define a buildService function, you should specify these headers in that function instead of including this option. This ensures that your buildService function doesn't inadvertently overwrite the values of any headers you provide via this option.

      const gateway = new ApolloGateway({
        introspectionHeaders: {    Authorization: 'my-header'  }});
    • logger: Logger

      A logging implementation to be used in place of console. The implementation must provide the methods which satisfy the requirements of the Logger interface (i.e. it must provide debug, info, warn and error methods). When a custom logger is provided, it will receive all levels of logging and it is up to the logger itself to determine how it wishes to handle each level. When a custom logger is not provided, Gateway will default to outputting warn and error levels unless debug: true is specified, in which case it will output all log levels (i.e. debug through error).

      Additionally, this logger will be made available on the GraphQLRequestContext and available to plugins. This allows a plugin to, e.g., augment the logger on a per-request basis within the requestDidStart life-cycle hook.

    • debug: Boolean

      If true, the gateway logs startup messages, along with the query plan for each incoming request. The default value is false.

    • fetcher: typeof fetch

      When specified, overrides the default Fetch API implementation which is used when communicating with downstream services. By default, make-fetch-happen is used with its own defaults. Another compliant implementation can be provided (e.g. node-fetch by setting fetcher: require('node-fetch')) or different default options for make-fetch-happen can be defined entirely. E.g.:

      const gateway = new ApolloGateway({
        /* ... */
        fetcher: require('make-fetch-happen').defaults({
          onRetry() {
            console.log('we will retry!')
        /* ... */
    • serviceHealthCheck: boolean

      When set to true, the gateway will issue a small query ({ __typename }) to its downstream services on load and on schema update. On load, the gateway will throw an error if any of the requests fail. On schema update, the gateway will not roll over to the new schema or service configuration if any of the requests fail, but it will try again at the next poll interval.

    • experimental_approximateQueryPlanStoreMiB: number

      This property is experimental. It may be removed or change at any time, even within a patch release.

      When set, this sets the approximate size of the query plan store (in MiB). This cache is used to save query plans for re-use on subsequent queries which resolve to the same queryHash (a SHA-256 of incoming operation).

      When this property is omitted, the cache is still enabled with a default size of 30MiB, which is generally sufficient unless the server is processing a high number of unique operations.


An ApolloGateway instance, which you then pass as the gateway configuration option to the ApolloServer constructor, like so:

const server = new ApolloServer({
  gateway: new ApolloGateway({ serviceList: [...] }),


Calling this function on the gateway will issue a small query ({ __typename }) to each downstream service to ensure they are all responsive. This function throws on failure and returns a Promise to be awaited.


  • serviceMap: DataSourceMap

    A map of data sources can optionally be provided to this function in order to modify where the health checks will be issued. By default, the gateway will use the existing this.serviceMap for issuing the health check requests.


A RemoteGraphQLDataSource object represents a connection between your federated gateway and one of your implementing services.

You can customize this connection by defining a subclass of this class and overriding its willSendRequest and/or didReceiveResponse methods:

  • The willSendRequest method lets you modify your gateway's requests to the implementing service before they're sent.
  • The didReceiveResponse method lets you modify the implementing service's responses before the gateway passes them along to the requesting client.

These methods are described in detail below.

constructor(options): RemoteGraphQLDataSource


  • options: Object

    An object that contains configuration options for the data source.

    Supported options include:

    • url: string (required)

      The implementing service's URL for sending fetch requests via HTTP.

    willSendRequest: (requestContext: {request: GraphQLRequest, context: Record<string, any>}) => Promise<void>

    Override this method to customize the structure of each fetch that's sent to the implementing service. The method accepts an object that contains both the original incoming request and the current context.

    The example below demonstrates using the willSendRequest method to add an x-user-id HTTP header to every request the gateway sends to an implementing service:

    class AuthenticatedDataSource extends RemoteGraphQLDataSource({
      willSendRequest({ request, context }) {    request.http.headers.set('x-user-id', context.userId);  }});

    didReceiveResponse: (requestContext: {request: GraphQLRequest, response: GraphQLResponse, context: Record<string, any>}) => Promise<GraphQLResponse>

    Override this method to customize the gateway's behavior after completing a fetch to the implementing service. The method receives an object (a GraphQLRequestContext) containing the request (a GraphQLRequest), the implementing service's response (a GraphQLResponse), and the current context as parameters. This allows modification of the context and the final result of the fetch.

    The http property on the request and response objects will contain additional HTTP-specific properties, like headers.

    Any implementation of this method must return an object that matches the structure of a GraphQLResponse (i.e., it should include http, data, errors, and/or extensions fields). If no modifications are necessary, simply return the original response.

    class CookieDataSource extends RemoteGraphQLDataSource {
      didReceiveResponse({ response, request, context }) {
        const cookie = request.http.headers.get('Cookie');
        if (cookie) {
        // Return the response back, even when unchanged.
        return response;
Edit on GitHub