how to use axios helper setToken inside .onRequest interceptor

Viewed 1707

I am using both nuxt-auth and nuxt-axios modules. I want to intercept every axios requests and check if my JWT access token is almost expired, if so, I want to update it. I the wrote a small extension to nuxt-auth as follow. My problem is that , once I get the new Token, $auth.setToken(strategy,newToken) and $axios.setToken(newToken) don't seem to make the expected updates. How then should I be using the interceptors and helpers ? I'm not sure it's the right place/way to use them

var jwtDecode = require("jwt-decode")

export default function({$auth, $axios}) {
  const strategy = "local"

  $axios.onRequest( async(config) => {
    if ($auth.loggedIn) {
      let refreshToken = "some confidtion"

      if (refreshToken) {
        try {
          await refreshAccessURL()
        } catch (error) {
          return Promise.reject(error)
        }
      }
    }
    return config
  })

  async function refreshAccessURL() {
    const refresh = $auth.getRefreshToken(strategy)
    try {
      const { access } = await $axios.$post(refreshURL, { refresh })
      const newToken = "Bearer " + access
      $auth.setToken(strategy, newToken)
      $axios.setToken(newToken)

      return newToken

    } catch (e) {
      $auth.logout()
      throw new Error(e)
    }
  }
}
1 Answers

You can add interceptor like below inside plugins/axios.js

export default function({ $axios }) {
  $axios.onRequest((config) => {
     config.headers['Authorization'] = `Bearer abc`;
  });
}
Related