apollo icon indicating copy to clipboard operation
apollo copied to clipboard

Add custom headers on request

Open tim-hanssen opened this issue 1 year ago • 7 comments

Your use case

We are looking for a way to add a custom defined header on the useAsyncQuery function of the client. In our case the visitors Customer Id needs to be added to some requests. But it seems we are not able to override the headers from the query location.

      const query = gql`
        query getShips($limit: Int!) {
          ships(limit: $limit) {
            id
            name
          }
        }
      `
      const variables = { limit: 5 }
      const { data } = await useAsyncQuery(query, variables)

The solution you'd like

I would be nice to add custom headers like below, they should than be merged with the auth headers specified when defining the client.

const query = gql`
  query getShips($limit: Int!) {
    ships(limit: $limit) {
      id
      name
    }
  }
`
const variables = { limit: 5 }
const headers = { customer-id: "123456789" }

const { data } = await useAsyncQuery(query, variables, headers)

Possible alternatives

No response

Additional information

No response

tim-hanssen avatar May 17 '23 14:05 tim-hanssen

I would also like to have this option, it would be very useful

CeruttiMaicon avatar May 22 '23 03:05 CeruttiMaicon

After many failed attempts and a lot of conversation with ChatGPT I managed to arrive at this palliative. I don't know if this is the best way to solve this problem. But in my application it is working.

packge.json

{
  "private": true,
  "version": "1.0.0",
  "devDependencies": {
    "@nuxtjs/apollo": "5.0.0-alpha.6",
  },
  "dependencies": {
    "@vuestic/nuxt": "^1.0.14",
    "vue": "^3.3.4",
  }
}

I created this middleware that does the magic

middleware/apollo.global.ts

import { defineNuxtPlugin } from '#app'
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core'
import { setContext } from '@apollo/client/link/context'

export default defineNuxtPlugin(nuxtAppMain => {
  
  const getTenant = () => (window ? window.location.hostname.split('.')[0] : '')
  const getApiUrl = () => (window ? window.origin.replace(getTenant(), 'api').replace(':3000', '') : '')

  const httpLink = new HttpLink({ uri: `${getApiUrl()}/graphql`, })

  const token = localStorage.getItem('userToken'); // Recuperar o token do localStorage

  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        'x-tenant': getTenant(),
        'Authorization': token ? `Bearer ${token}` : "", // Token in header
      },
    }
  })

  const apolloClient = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
  })

  const nuxtApp = useNuxtApp()
  
  nuxtApp._apolloClients.default = apolloClient
})

It's working for me, I'll leave it here in case it helps anyone else, but I'd prefer the functionality described here to be the definitive one and not this middleware creation just to recreate the graphql instance and give me the possibility to adjust the headers. It should be simpler.

CeruttiMaicon avatar May 29 '23 13:05 CeruttiMaicon

Nice work @CeruttiMaicon let's see if it works for us too @Kevintjuhz

tim-hanssen avatar May 29 '23 14:05 tim-hanssen

Just curious – what is the use case for this? If the customer_id influences the query result, shouldn't it be a variable in the query itself?

slavanossar avatar Jun 14 '23 01:06 slavanossar

Hi @slavanossar the customer_id is intercepted at the edge, there it's matched against customer segments and returns the right version. Adding it to the query as a variable would completely bypass the cdn caches.

tim-hanssen avatar Jun 14 '23 16:06 tim-hanssen

Nice work @CeruttiMaicon let's see if it works for us too @Kevintjuhz

Did it work correctly for you? @tim-hanssen

CeruttiMaicon avatar Jun 23 '23 19:06 CeruttiMaicon

I would also like to see this functionality.

@CeruttiMaicon, your provided code is a middleware but uses the defineNuxtPlugin function?

WordsofDefiance avatar Jul 28 '23 19:07 WordsofDefiance