I am building a web application with Vue.js. I am trying to add Auth0 by going through the Auth0 Vue SDK Quickstart. I am able to get the user to log in and display their user information on a profile page. $auth is valid in all of my Vue components.
The issue is I am trying to create an API client with Axios that uses an interceptor to add an Authorization header. When I try to use $auth.getTokenSilently()
$auth
is always null
. I’m doing something very similar to Using Auth0 SPA with Axios Wrapper - #3 by vanpyrzericj - Get Help - Vue Forum. I also tried to use this The prototype this.$auth in Vue main.js always null - #3 by damir to fix the issue but getInstance()
is null.
Here is my main.js
Vue.use(Auth0Plugin, {
domain,
clientId,
onRedirectCallback: appState => {
router.push(
appState && appState.targetUrl
? appState.targetUrl
: window.location.pathname
const myApp = new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
export default myApp;
Repository.js
import axios from 'axios';
import myApp from "@/App";
const baseDomain = 'http://localhost:8000';
const baseURL = `${baseDomain}/api`;
export const httpClient = axios.create({
baseURL: baseURL,
headers: {
"Context-Type": "application/json"
}
});
httpClient.interceptors.request.use(async (config) => {
const token = await myApp.$auth.getTokenSilently();
config.headers['Authorization'] = `Bearer ${token}`;
return config
}, (error) => {
return Promise.reject(error);
})
Then in my store.js (Vuex) I am using a factory pattern to use the httpClient. It seems the interceptor is running before Auth0 is fully loaded. If you have any ideas please let me know!
Seems like I should make sure auth0 is ready before anything else.