I have a non monorepo nestJs graphql microservices app, and opted for Apollo federation gateway. I have an authentication server which works fine and sets cookies to header, only problem is when calls are made through apollo gateway set-cookie headers are not being set, and request headers cookies are not passed to microservices.
this is my gatewayModule
@Module({
imports: [
GraphQLModule.forRoot<ApolloGatewayDriverConfig>({
driver: ApolloGatewayDriver,
gateway: {
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
{
name: 'users',
url: 'http://localhost:9999/graphql',
},
{
name: 'posts',
url: 'http://localhost:9119/graphql',
},
{
name: 'comments',
url: 'http://localhost:9229/graphql',
},
],
}),
},
}),
],
})
I have found a solution, add the following class and import it to app.module
// graphql-data-source.ts
import {
GraphQLDataSourceProcessOptions,
RemoteGraphQLDataSource,
} from '@apollo/gateway';
import { GraphQLDataSourceRequestKind } from '@apollo/gateway/dist/datasources/types';
export class GraphQLDataSource extends RemoteGraphQLDataSource {
didReceiveResponse({ response, context }): typeof response {
const cookies = response.http.headers?.raw()['set-cookie'] as
| string[]
| null;
if (cookies) {
context?.req.res.append('set-cookie', cookies);
}
return response;
}
willSendRequest(params: GraphQLDataSourceProcessOptions) {
const { request, kind } = params;
if (kind === GraphQLDataSourceRequestKind.INCOMING_OPERATION) {
const cookie =
params?.incomingRequestContext.request.http.headers.get('Cookie');
request.http.headers.set('Cookie', cookie);
}
}
}
then edit app.module
....
GraphQLModule.forRoot<ApolloGatewayDriverConfig>({
driver: ApolloGatewayDriver,
gateway: {
buildService: (args) => new GraphQLDataSource(args),
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
....