'Add header to all apollo query

As the title suggest, I am trying to add a header to all queries and mutations made by apollo. I know I can do

context: {
  headers: {
    'Accept-Language': $this.i18n.current;
  }
}

but that is only for one query or mutation. I am using nuxt with vue and my current nuxt.config.js is as follows

apollo: {
    clientConfigs: {
      default: '~/plugins/apollo-config.js'
    },
    defaultOptions: {
      $query: {
        fetchPolicy: 'network-only',
        context: { // does not work
          headers: {
            "Accept-Language": $this.i18n.current, // not sure if this works as it is in config
          }
        }
      }
    },
    errorHandler: '~/plugins/apollo-error-handler.js'
  },

I'm pretty sure I'm using context wrong in this case but not sure how else I should do it. Any help would be very much appreciated.



Solution 1:[1]

I'm not at all a professional regarding GraphQL but last year, I've achieved something that works well (with a JWT header), here is what I had back at the time

nuxt.config.js

apollo: {
  clientConfigs: {
    default: '@/plugins/nuxt-apollo-config.js',
  },
  defaultOptions: {
    $query: {
      loadingKey: 'loading',
      fetchPolicy: 'network-only',
    },
  },
  authenticationType: 'Bearer',
},

and here is my
nuxt-apollo-config.js file

import { setContext } from 'apollo-link-context'
import { from } from 'apollo-link'
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
import { createHttpLink } from '@apollo/client/core'
import schema from '../apollo/schema.json'

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData: schema,
})

export default ({ app, $config: { baseUrlGraphql } }) => {
  const headersConfig = setContext(() => ({
    credentials: 'same-origin',
    headers: {
      Authorization: app.$cookies.get('auth._token.local'),
      'x-company-id': app.$cookies.get('company_id'),
    },
  }))

  const cache = new InMemoryCache({ fragmentMatcher, resultCaching: false })

  return {
    defaultHttpLink: false,
    link: from([
      headersConfig,
      createHttpLink({
        credentials: 'include',
        uri: baseUrlGraphql,
        fetch: (uri, options) => {
          return fetch(uri, options)
        },
      }),
    ]),
    cache,
  }
}

import { setContext } from 'apollo-link-context' worked well for me. I'm not sure that it's the best because there is maybe something baked-in right now but this one worked for me last year.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kissu