apollo
apollo copied to clipboard
Add custom headers on request
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
I would also like to have this option, it would be very useful
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.
Nice work @CeruttiMaicon let's see if it works for us too @Kevintjuhz
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?
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.
Nice work @CeruttiMaicon let's see if it works for us too @Kevintjuhz
Did it work correctly for you? @tim-hanssen
I would also like to see this functionality.
@CeruttiMaicon, your provided code is a middleware but uses the defineNuxtPlugin
function?