API Reference: @apollo/gateway
Apollo Gateway API reference
This API reference documents the exports from the @apollo/gateway
package.
class ApolloGateway
The core class of Apollo Server's federated gateway implementation. For an
example of using ApolloGateway
, see The gateway.
Methods
constructor
Returns an initialized ApolloGateway
instance, which you can then pass as the gateway
configuration option to the ApolloServer
constructor, like so:
const server = new ApolloServer({gateway: new ApolloGateway({serviceList: [// ...]}),});
Takes an options
object as a parameter. Supported fields of this object are described below.
Examples
Providing a serviceList
and headers to authorize introspection
const gateway = new ApolloGateway({serviceList: [{ name: 'products', url: 'https://products-service.dev/graphql' },{ name: 'reviews', url: 'https://reviews-service.dev/graphql' }],introspectionHeaders: {Authorization: 'Bearer abc123'}});
Configuring the subgraph fetcher
If you provide a buildService
function to the constructor of ApolloGateway
, the function is called once for each of your graph's subgraphs. This function can return a RemoteGraphQLDataSource
with a custom fetcher
, which is then used for all communication with subgraphs:
const gateway = new ApolloGateway({buildService({ url, name }) {return new (class extends RemoteGraphQLDataSource {fetcher = require('make-fetch-happen').defaults({onRetry() {console.log('We will retry!')},});})({url,name,});}});
Configuring the managed federation fetcher
This only configures the fetcher that your gateway uses to fetch managed federation configuration from Apollo.
See also Configuring the subgraph fetcher.
const gateway = new ApolloGateway({fetcher: require('make-fetch-happen').defaults({onRetry() {console.log('We will retry!')},}),});
Options
Name / Type | Description |
---|---|
| You provide your supergraph schema to the gateway with this option. You can provide it as a When When
When If you are using managed federation, do not provide this field. If you aren't using managed federation, either this field or |
| This option is deprecated in favor of the drop-in replacement, An array of objects that each specify the You can specify any string value for the If you are using managed federation, do not provide this field. If you aren't using managed federation, either this field or |
| This option is deprecated in favor of the drop-in replacement, An object (or an optionally async function returning an object) that contains the names and values of HTTP headers that the gateway includes only when making introspection requests to your subgraphs. If you are using managed federation, do not provide this field. If you define a |
| If The default value is |
| An object to use for logging in place of If you provide this value, the gateway automatically logs all messages of all severity levels ( This logger is automatically added to the |
| Specifies which Fetch API implementation to use with managed federation when fetching configuration from Apollo. By default, the gateway uses the default configuration of As shown in the example above, you can also provide |
| If On startup, the gateway throws an error if any of these requests fail. On schema update, the gateway does not roll over to the new schema or graph configuration if any of these requests fail. The gateway retries the requests at each polling interval until they succeed. The default value is |
| A list of Apollo Uplink URLs the gateway uses to poll for its managed configuration. For details and defaults, see Apollo Uplink. Provide this field only if you are using managed federation and your use case specifically requires it (this is uncommon). |
| The maximum number of times the gateway retries a failed poll request to Apollo Uplink, cycling through its list of The default value is to try each of your uplinkEndpoints three times (i.e., 5 retries with the default list of two endpoints). Provide this field only if you are using managed federation. |
| Specify this option as a fallback if Uplink fails to provide a polling interval. This will also take effect if |
| Define this function to customize your gateway's data transport to some or all of your subgraphs. This customization can include using a protocol besides HTTP. For details, see The |
The buildService
function
If you provide this function, the gateway calls it once for each subgraph. 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 a subgraph:
class AuthenticatedDataSource extends RemoteGraphQLDataSource {willSendRequest({ request, context }) {request.http.headers.set('x-user-id', context.userId);}}const gateway = new ApolloGateway({// ...other options...buildService({ name, url }) {return new AuthenticatedDataSource({ url });},});
Experimental options
These options are experimental. They might be removed or change at any time, even within a patch release.
Name / Type | Description |
---|---|
| Sets the approximate size (in MiB) of the gateway's query plan store. This cache is used to save query plans for reuse on subsequent queries that resolve to a previously observed The default value is |
serviceHealthCheck
When called, the gateway sends a small query ({ __typename }
) to each subgraph to verify that they're all responsive. This function throw
s on failure and returns a Promise
to be await
ed.
Parameters
Name / Type | Description |
---|---|
| If provided, the gateway sends health check requests to only the data sources included in the map. By default, the gateway uses |
class RemoteGraphQLDataSource
Represents a connection between your federated gateway and one of your subgraphs.
You can customize this connection by extending this class and overriding its willSendRequest
and/or didReceiveResponse
methods:
- Override
willSendRequest
to modify your gateway's requests to the subgraph before they're sent. - Override
didReceiveResponse
to modify the subgraph's responses before the gateway passes them along to the requesting client.
These methods are described in detail below.
Methods
constructor
Returns an initialized RemoteGraphQLDataSource
instance:
const productsDataSource = new RemoteGraphQLDataSource({url: 'https://products-service.dev/graphql'});
Takes an options
object as a parameter. Supported fields of this object are described below.
Options
Name / Type | Description |
---|---|
| Required. The subgraph's URL for sending fetch requests via HTTP. |
| If The subgraph must also enable support for APQ for the gateway to use this feature (Apollo Server enables APQ by default). |
willSendRequest
Override this method in a subclass to modify each outgoing fetch request before it's sent to the subgraph:
// Adds an `x-user-id` header to each outgoing fetch requestclass AuthenticatedDataSource extends RemoteGraphQLDataSource({willSendRequest({ request, context }) {request.http.headers.set('x-user-id', context.userId);}});
This method takes a requestContext
object that contains both the original unmodified request
and the current context
.
didReceiveResponse
Override this method in a subclass to customize the gateway's behavior after it completes a fetch to the subgraph, but before it sends a response to the requesting client:
class CookieDataSource extends RemoteGraphQLDataSource {didReceiveResponse({ response, request, context }) {const cookie = request.http.headers.get('Cookie');if (cookie) {context.responseCookies.push(cookie);}// Return the response, even when unchanged.return response;}}
This method takes a requestContext
object that contains:
- The subgraph's
response
- The gateway's
request
to the subgraph - The current operation's
context
This enables you to modify any combination of the operation's context
and the response of the fetch.
The http
property of the request
and response
objects contains additional HTTP-specific properties, such as headers
.
This method must return an object that matches the structure of a GraphQLResponse
. If no modifications are necessary, return the original response
.
didEncounterError
Override this method in a subclass to customize the gateway's behavior after it encounters an error while communicating with the subgraph or while parsing its response (e.g., if the response is not well-formed JSON).
If you don't override this method, the default implementation throw
s the error, like so:
class MyDataSource extends RemoteGraphQLDataSource {didEncounterError(error, fetchRequest, fetchResponse, context) {throw error;}}
Note that if you don't throw error
(or a different Error
) in this method, error
is thrown immediately after this method returns.
This method takes the following positional parameters:
Name / Type | Description |
---|---|
| The error that occurred during communication. |
| The details of the |
| The details of the |
| The |
class IntrospectAndCompose
IntrospectAndCompose
is a development tool for fetching and composing subgraph SDL into a supergraph for your gateway. Given a list of subgraphs and their URLs, IntrospectAndCompose
will issue queries for their SDL, compose them into a supergraph, and provide that supergraph to the gateway. It can also be configured to update via polling and perform subgraph health checks to ensure that supergraphs are updated safely. IntrospectAndCompose
implements the SupergraphManager
interface and is passed in to ApolloGateway
's supergraphSdl
constructor option.
IntrospectAndCompose
is the drop-in replacement for serviceList
.
Methods
constructor
Returns an initialized IntrospectAndCompose
instance, which you can then pass to the supergraphSdl
configuration option of the ApolloGateway
constructor, like so:
const server = new ApolloServer({gateway: new ApolloGateway({supergraphSdl: new IntrospectAndCompose({subgraphs: [// ...],}),}),});
Takes an options
object as a parameter. Supported properties of this object are described below.
Examples
Providing a subgraphs
list and headers to authorize introspection
const gateway = new ApolloGateway({supergraphSdl: new IntrospectAndCompose({subgraphs: [{ name: 'products', url: 'https://products-service.dev/graphql' },{ name: 'reviews', url: 'https://reviews-service.dev/graphql' },],introspectionHeaders: {Authorization: 'Bearer abc123'},}),});
Configuring the subgraph fetcher
IntrospectAndCompose
uses the data sources constructed by ApolloGateway
. To customize the gateway's data sources, you can provide a buildService
function to the ApolloGateway
constructor. In the example below, IntrospectAndCompose
makes authenticated requests to the subgraphs
via the AuthenticatedDataSource
s that we construct in the gateway's buildService
function.
const gateway = new ApolloGateway({buildService({ name, url }) {return new AuthenticatedDataSource({ url });},supergraphSdl: new IntrospectAndCompose({subgraphs: [{ name: 'products', url: 'https://products-service.dev/graphql' },{ name: 'reviews', url: 'https://reviews-service.dev/graphql' },],}),});
Options
Name / Type | Description |
---|---|
| An array of objects that each specify the The For Studio users, subgraph names must:
|
| An object (or an optionally async function returning an object)that contains the names and values of HTTP headers that the gateway includes only when making introspection requests to your subgraphs. If you define a |
| Specify this option to enable supergraph updates via subgraph polling. |
| This option applies only to subgraphs that are configured for polling via the This option is the |
| An object to use for logging in place of
|