didReceiveResponse update context

We are currently using Apollo Gateway with a couple of subgraphs. After first logon, the frontend (a reactJS app) will query one of the subgraphs. We actually want to store some of the details fetched in that subgraph into the Apollo Context.

To do this, I was thinking of using RemoteGraphQLDataSource and implement some code in the 2 methods provided there as follows:

async willSendRequest({ request, context }) {
  request.http.headers.set("user", context.user ? JSON.stringify(context.user) : null);
  }
}

async didReceiveResponse({ response, request, context }) {
  if(response.data != undefined && response.data.post_login != undefined) {
    context.user.features = response.data.post_login.features;
  }

  return response;
}

It seems that we can correctly retrieve the data needed in the didReceiveResponse; this data is coming from one of our subgraphs. Setting the context.user.features is also possible. However the context doesn’t seem to contain this data anymore in the willSendRequest.

My question is: if we modify the context in the willSendRequest function, will that change be available everywhere in the context or just for that specific request/response?

Funny thing to note is that this is working on my localhost but not when we deploy it via Docker.

Hey @brampurnot, context is created and modified on a per-request basis. You’ve got the right idea for using headers to share context with subgraphs though.

Gateway (well, actually ApolloServer) creates the context object at the beginning of a request and shares that object across all requests from the same query plan. Modifications to the context object by one data source should be seen by data sources handling serial requests that happen after the modification. Hope that helps.

More info here: The graph router - Apollo GraphQL Docs

Thanks! That helps a lot