Apollo Client - Build cache keys with request header

Hi there,

I currently ingest a GraphQL API that can return different data based off of certain request headers. For example, the following query:

query {
  items {
    id
    title
  }
}

can return different result sets depending on whether a specific header is also set on the request (ie. role: admin)

What I’m noticing is that if I make this query two times, one with the above header set, and one without, the second query will pull the incorrect result set from cache since it seems that Apollo thinks they’re the same query (which they are, but they just have different headers).

Is there a way to define a type policy such that it can pull in the request headers or context when determining the cache key? Or is there some other workaround that informs Apollo that they are different queries?

1 Like

Hello, good question! To the best of my understanding, there isn’t a straightforward way to cache multiple values for a single schema field based solely on different header values. However, you can cache multiple values for a single field based on different argument values.

Even if you continue to provide your query’s associated role via a header, you can also modify your schema to support providing that role via an argument, like so:

query {
  items(role: "admin") {
    id
    title
  }
}

Then, if you also execute this query with a different role or even no role, by default the cache stores those results separately. Here’s what the root query object in the cache would look like after a couple such executions with different roles:

ROOT_QUERY
  __typename: "Query"

  items({"role":"admin"}):
    [...]

  items({"role":"user"}):
    [...]
1 Like

Hi Stephen!

Thank you for your reply. Unfortunately, the decision to send role information through the header is locked down, and we therefore wouldn’t want to duplicate that through an argument (even if it ends up being discarded).

I have found a few feature requests asking for the same capability:

Do you have some insight into whether this is on the feature roadmap?

I have the same issue.
I am using Authorization Header btw.
Any luck by any chance?

This is a great solution btw why didn’t I thought about it.
I just have to change all the 4 client projects and 1 server project.
:clap: :clap: :clap: