The prototype this.$auth in Vue main.js always null

Hi,

I’m trying to integrate Auth0 with my Vue app. I use the following tutorials as guide:

  1. https://auth0.com/docs/quickstart/spa/vuejs/01-login
  2. https://auth0.com/docs/quickstart/spa/vuejs/02-calling-an-api

However, I’m unable to access this.$auth in main.js of the Vue app. I’ve successfully logged in with Auth0 and in the app I can access all $auth.user in the template (*.vue files). The this.$auth in Navbar.vue script can be accessed with no problem at all for calling the this.$auth.logout function. The same also work for App.vue.

What I actually need is to get the access token with this.$auth.getTokenSilently(). Which is needed to call an Auth0 protected API throughout the app especially in my store files (vuex).

From the tutorial I know that the plugin should make the $auth & this.$auth to be available throughout the Vue app. But somehow I’m unable to access in in main.js. It always return null. Am I missing some things? I’m still a Vue noob by the way.

Thanks!

1 Like

It seems that this.$auth is not updated without refresh of the page (login and callback was at the page home). I manage to add the login info into vuex store in another page, callback & redirect to home with success. Is this a clean solution? Or is there a better way to do it? TIA

Dealing with the same issue here, I want to pass accessToken from getTokenSilently() to apolloClient, but unable to do so. For the moment I’m using localStorage to store accessToken, but I believe there is a better solution. Maybe @steve.hobbs can help us out?

1 Like

@faizalec As you’ve discovered, this.$auth won’t be available inside main.js as it only get applied to Vue components.

However, the wrapper supplied with the sample exports a getInstance function that you can use to get access to the same thing. You do need to be a bit careful, as methods like getTokenSilently (which comes from the SPA JS SDK) only work once the SDK has been completely initialized. i.e., when loading is false. So you need to set up a $watch on this to make sure you can access the token at the right time (assuming you’re logged in).

Something like this snippet should work. Place it inside main.js, with the import at the top (amending what you might already have) and the $watch code after the Vue.use(Auth0Plugin...) call:

// Import getInstance from the auth wrapper
import { Auth0Plugin, getInstance } from './auth';

// ...

const instance = getInstance();

instance.$watch("loading", async loading => {
  if (!loading && instance.isAuthenticated) {
    const token = await instance.getTokenSilently();
    console.log(token);
  }
});

Hope that helps

3 Likes

Thanks for sharing the knowledge Steve!

@steve.hobbs thank you, this will definitely help!

1 Like

Perfect @damir! Let us know if you have any other questions!

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