Issue with $auth being null

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 https://forum.vuejs.org/t/using-auth0-spa-with-axios-wrapper/79187/3. I also tried to use this The prototype this.$auth in Vue main.js always null 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.

After trying a few different solutions this one worked! Make sure to await on the action. Let me know if you have any questions.

1 Like

Thanks for sharing it with the rest of community!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.