Apollo-module: How to set global custom dynamic header?

Created on 5 Jun 2020  路  4Comments  路  Source: nuxt-community/apollo-module

Hi!
I need to send a header which is determined by the presence of a certain cookie.

Example:

nuxt.config.js
```
httpLinkOptions: {
headers: {
'custom-header': {{ myCookie }},
},
},
````

Please tell me how to do this?

Most helpful comment

Can we somehow apply it to the whole Apollo configuration ?
I do have several components using the same headers over and over again.
Is there a way to change it globally ? 馃槃

Also once spent a lot of time on this problem.

I got it like this:

nuxt.config.js

apollo: {
    clientConfigs: {
      default: '@/plugins/apollo-client/default.js',
    },
}

default.js

import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { from } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';

export default ({ app, store }) => {
  const headersConfig = setContext(() => ({
    headers: {
      'X-Language': store.state.language, // example language header
    },
  }));

  const httpLink = new HttpLink({
    uri: YOUR_ENDPOINT,
  });

  const link = from([headersConfig, httpLink]);
  const cache = new InMemoryCache();

  return {
    link,
    cache,
    defaultHttpLink: false,
  };
};

All 4 comments

Headers are available in context.
You can call your queries/mutations with custom headers this way:

await client.query({
  query,
  'context': {
    'headers': {
      'custom-header': 'value',
    },
  },
});

Can we somehow apply it to the whole Apollo configuration ?
I do have several components using the same headers over and over again.
Is there a way to change it globally ? 馃槃

Can we somehow apply it to the whole Apollo configuration ?
I do have several components using the same headers over and over again.
Is there a way to change it globally ? 馃槃

Also once spent a lot of time on this problem.

I got it like this:

nuxt.config.js

apollo: {
    clientConfigs: {
      default: '@/plugins/apollo-client/default.js',
    },
}

default.js

import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { from } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';

export default ({ app, store }) => {
  const headersConfig = setContext(() => ({
    headers: {
      'X-Language': store.state.language, // example language header
    },
  }));

  const httpLink = new HttpLink({
    uri: YOUR_ENDPOINT,
  });

  const link = from([headersConfig, httpLink]);
  const cache = new InMemoryCache();

  return {
    link,
    cache,
    defaultHttpLink: false,
  };
};

Not the official way I guess (there is none I guess ?) but yeah, the store may work.
Thanks for the idea buddy ! 馃檹馃徎

Was this page helpful?
0 / 5 - 0 ratings