[Vuejs]-Use Vue.js plugin in js service module

1👍

The service should be initialized inside Vue. It can just be injected with initialization data:

  init(token) {
    this.lqdApi = axios.create({
      baseURL: process.env.lqdApiBaseUrl,
      headers: { Authorization: `Bearer ${token}` }
    });
    return this;
  },

The problem here is that async created is a potential antipattern, it doesn’t prevent child components from being initialized when auth0Client and therefore api-service aren’t ready but used by components. If this is the case, one of possible solutions is to make Axios instance available on Vue prototype, like shown here. The instance needs to be created immediately, but a token can be provided to it asynchronously with interceptors because they support promises.
It can be written as a plugin and become available on Vue instance like $auth:

  install(Vue, options) {
    Vue.prototype.$axios = axios.create();
  },
  created() {
    if (this.$root === this) {
      this.$axios.interceptors.request.use(async config => {
        let auth0Client = await this.auth0ClientPromise;
        config.headers.Authorization = `Bearer ${auth0Client.getTokenSilently()}`;
        return config;
    }
  }

And a promise of Auth0 client instance should be available on Vue instance in order to be chained by Axios (and probably other things that may depend on it):

  this.auth0ClientPromise = createAuth0Client(...);
  this.auth0Client = await auth0ClientPromise;

Leave a comment