nuxt-modules / apollo

Nuxt.js module to use Vue-Apollo. The Apollo integration for GraphQL.
https://apollo.nuxtjs.org
MIT License
955 stars 198 forks source link

How to use dynamic Bearer token [Help] #421

Closed DidoMarchet closed 1 year ago

DidoMarchet commented 2 years ago

Hi guys, I cannot figure out how to use a Bearer code obtained after a login.

I've got this situation in asyncData:

const token = await myTokenFn() //  A function that return a token

const data = await this.$apollo.query({
    query,
    variables,
    // I NEED TO PASS AND USE MY TOKEN
})

Any advices or example is appreciated!

Thanks in advance and kind regards,

Davide

MuhaddiMu commented 2 years ago

Were you able to workaround with this?

hermesalvesbr commented 1 year ago

I'm also looking for a way to use bearer token.

DidoMarchet commented 1 year ago

Hi, I do that: in the apollo configuration file I added the configuration of the client:

export default {
  apollo: {
    clientConfigs: {
      saleor: '~/configuration/apollo/config-saleor.js',
    },
    errorHandler: '~/configuration/apollo/error-handler.js',
  },
}

and in the configuration file of my client (config-saleor.js) I do:

export default ({ store, app }) => {
  return {
    httpEndpoint: process.env.NUXT_ENV_SALEOR_GQL_URL,
    getAuth: () => {
      return store.state.saleor.user.user &&
        store.state.localStorage?.auth?.token &&
        !app.$useSaleor.fetch.tokenNeedRefresh()
        ? `Bearer ${store.state.localStorage?.auth?.token}`
        : ''
    },
  }
}

so I check if the token is valid (this is my own check but you can use yours).

I refresh the token during the navigation using a router middleware. Note: I use my own chekc and function in the if state and in the dispatch do you can use your owns.

export default async function ({ store, app }) {
  if (app.$useSaleor.fetch.tokenNeedRefresh()) {
    await store.dispatch('saleor/user/updateUser', {
      key: 'refreshToken',
      dataForm: {
        refreshToken: store.state.localStorage?.auth?.refreshToken,
      },
    })
    store.dispatch('localStorage/setAuth')
  }
}

Thanks and kind regards,

Davide