Search code examples
graphqlapolloapollo-federation

How to set different header for different subgraph via ApolloGateway?


I am using Apollo gateway to build a graphql federation service. Below is the demo code:

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',
    },
  }),
});

As you can see there are 2 subgraphs products and reviews, and there is also a introspectionHeaders which gives authorization. My questions is:

  • How can I specify different header for different subgraph? In above example, the header applies on both subgraph

Solution

  • you can use use buildService...something this:

      const authMap = {
        'products': 'abc',
         'reviews': 'xyz'
      }
    
      const gateway = new ApolloGateway({
        supergraphSdl: new IntrospectAndCompose({
          subgraphs: [
             { name: 'products', url: 'https://products-service.dev/graphql' },
             { name: 'reviews', url: 'https://reviews-service.dev/graphql' },
          ]
        }),
        buildService (item: ServiceEndpointDefinition) {
          const { url, name } = item
          return new RemoteGraphQLDataSource({
            url,
            willSendRequest (options: any) {
              const { request } = options
              request.http.headers.set('Authorization' `Bearer ${authMap[name]}`)
            }
          })
        }
      })