Auth0 client is null in Vue SPA component on page refresh

I finally came up with a similar solution to yours:

import { getInstance } from "./auth/authWrapper";

// ... Vue component:
created() {
    this.init(this.loadTokenIntoStore);
},
methods: {
    init(fn) {
        // have to do this nonsense to make sure auth0Client is ready
        var instance = getInstance();
        instance.$watch("loading", loading => {
            if (loading === false) {
                fn(instance);
            }
        });
    },
    async loadTokenIntoStore(instance) {
        await instance.getTokenSilently().then((authToken) => {
            // do authorized API calls with auth0 authToken here 
            // or load authToken in state store for other components to use
        });
    }
}

This happens on root component load. At this point I put the token into my Vuex store and it’s available to all my other components (until page refresh, which forces a new token retrieval).

I think the underlying issue here is that I wasn’t supposed to use the Vue SPA quickstart if I’m using a separate back end. In such a case, it appears as though the right thing to use is a machine to machine flow, which I believe can drop an authentication token cookie into the SPA on the callback rather than using a bearer token obtained from an asynchronous Auth0 client initialization. This is not very clear from the existing documentation, and it would be helpful if Auth0 placed a warning statement about it at the very beginning. I’ve invested a lot of hours in getting this setup running as-is, and at some point now I have to go back and convert it to the other flow.

Thanks for your response, it looks a little cleaner than mine so I’ll probably give it a whirl!

2 Likes