How to get access token in my axios global config file - Vue 3

Hello, hope you’re all well :slight_smile:

I’m trying to avoid manually calling the getAccessTokenSilently() line everytime I want to call my API and just use the Axios global defaults. I’ve created an axios.js file in my application that contains the following:

//Import Axios Library and Auth0
import axios from 'axios';
import { useAuth0 } from "@auth0/auth0-vue"

//Create instance of axios
const instance = axios.create({
    baseURL: 'http://localhost:5000/api/v1'
});

// Create a request interceptor for my instance and get accessToken on the fly
instance.interceptors.request.use(async (config) => {
    const { getAccessTokenSilently } = useAuth0();
    const accessToken = await getAccessTokenSilently();
    config.headers['Authorization'] = accessToken;
    return config;
}, (error) => {
    return Promise.reject(error)
});

export default instance;

Basically I’m trying to attach the accessToken using the request interceptor function but it won’t work and the authorization header doesn’t get added. Is this the correct way to do so? If not, can you please let me know best practices (if available).

I couldn’t find a proper method to retrieve an accessToken outside a component file in auth0 docs using the vue-sdk file.

I’m fairly new to this so any help is greatly appreciated :slight_smile:

EDIT:

Just on how I make my API calls, I’m using Pinia actions to invoke API requests by importing the axios config file and call the API endpoint. See the following pinia store code:

//Import the Pinia Library
import { defineStore } from 'pinia'
//Import the Axios Library for API calls
import axiosConfig from "@/config/axios.js"

export const useUserStore = defineStore('user', {
  state: () => ({
    user:{}
  }),
  getters: {
    getUser(state){
      return state.user
    }
  },
  actions: {
    async fetchUser(){
      try {
        const data = await axiosConfig.get('/profile')
        this.user = data.data
      } catch (error) {
        console.log("User Pinia error: " + error)
      }
    }
  },
})

Please let me know if you require more information!

Hi All,

Just following up on this as it’s been a week. Would I be able to get an answer sooner rather than later?

Thanks