How to Set Custom Response Header for a Specific Query in Apollo Server v4

Hi everyone,
I’m using Apollo Server v4 (standalone mode) in a Node.js project, and I’m wondering if it’s possible to set a custom response header only for a specific query, and based on some runtime condition.

For example, I want to do something like:

query {
  sensitiveData {
    info
  }
}

And if a certain condition is met during the resolver execution, I want to include a custom response header like:

X-Custom-Warning: true

I know with Express we can modify res.setHeader, but since I’m using the standalone setup, I’m not sure of the best way to achieve this in Apollo Server v4.

Any suggestions or workarounds would be greatly appreciated!

Hello!

You can use an Apollo Plugin to handle this, specifically the willSendResponse lifecycle method.

Another approach is to pass the response object through the context and modify it inside the resolver.

Thanks for the reply! Yes, I saw the general plugin approach using willSendResponse, but my challenge is a bit more specific.

What I’m trying to do is:

  • I have a specific query (e.g., sensitiveData)
  • Inside that resolver, I check for a condition (e.g., a threshold or some flag)
  • Only if that condition is met, I want to set a custom header in the response (e.g., X-Custom-Warning: true)
  • This header should not be set globally or for other queries

So basically, I want resolver-level control over whether to add a response header or not — without affecting other resolvers.

Is there a clean way to do this in Apollo Server v4 standalone mode? I’m open to using context, plugins, or any workaround that enables this level of control.

Appreciate any pointers!

In my previous answer, I mentioned an approach where you pass the response object through the context to the resolver, could you give it a try?

export const resolvers = {
  Query: {
    foo: (parent, args, context) => {
      const headers = new Headers({ "x-warning-123": "true" });
      context.res.setHeaders(headers);
      // ...
    }
  }
}
1 Like