Adding header in Apollo Client erases cookies in ReactJS GraphQL requests

We are using Apollo client to generate GraphQL queries from our React codebase, and everything has been working nicely.
Until now.

We have a new requirement to add a “traceId” header, and we are following the code examples in Advanced HTTP networking - Apollo GraphQL Docs

Specifically we are doing

const activityMiddleware = new ApolloLink((operation, forward) => {
  // add the recent-activity custom header to the headers
  operation.setContext(({ headers = {} }) => ({
    headers: {
      ...headers,
      'traceid': dbf55fea-93f9-4432-a093-e8651f5426c1
    }
  }));

However when we do this, we are finding that our traceid is indeed added, but then all of our cookies are removed!

Here is the response when we add the traceId

accept:*/*
content-type:application/json
Referer:http://localhost.ms.com:3000/sec-ch-ua:"Chromium";v="110", "Not A(Brand";v="24", "Google Chrome";v="110"
sec-ch-ua-mobile:?0
sec-ch-ua-platform:"Windows"
traceid:dbf55fea-93f9-4432-a093-e8651f5426c1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36

This is exactly the same response as the good call, except that this one has removed the Cookie header.

We need our cookies, they contain session information, etc. What is a developer to do?

Do you need to call the next Apollo link in your middleware function? The docs say you should call forward() to go to the next link.

Could also check the order you are specifying the links when instantiating ApolloClient object. Maybe the order is wrong and causing headers to be overwritten.

Yes we are already calling the forward

Hi @vgrazi :wave: I think you may be inadvertently leaving out properties of your context object in your link function. Could you let me know if the following helps?

const activityMiddleware = new ApolloLink((operation, forward) => {
  // add the recent-activity custom header to the headers
  operation.setContext((context) => ({
    ...context,
    headers: {
      ...context.headers,
      'traceid': dbf55fea-93f9-4432-a093-e8651f5426c1
    }
  }));

Hi Jeff , @vgrazi and I tried to add context and appended it as you have mentioned but didnt see traceId in the headers. we do see the cookies getting added