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

@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