How set a response header when doing a GraphQL request with Apollo Client in Astro

111 Views Asked by At

I am using Astro and Apollo Client.

I need to set a custom Response Header.

How to set a custom response header when doing a GraphQL request?

In my Apollo Client file:

const myCustomHeaderLink = new ApolloLink((operation, forward) => {
    return forward(operation).map((result) => {
        res.headers.set('My-Custom-Header', 'my-value'); // How to get access to the `response` here?
        return result;
    });
  });


export const client = new ApolloClient({
  cache: new InMemoryCache(),
  ssrMode: true,
  link: from([myCustomHeaderLink, httpLink]),
});
1

There are 1 best solutions below

3
Michel Floyd On

On the client you set a request header and get a response header. Assuming you are trying to do the former then you'll want to use setContext in a custom link:

import { setContext } from '@apollo/client/link/context';

const myCustomHeaderLink = setContext(
  async (_, { headers: existingHeaders }) => {
    const headers = { 'x-my-header': 'myHeaderValue', ...existingHeaders };
    return { headers };
});

Then add this link to your link chain.