Vue: Calling an API

Gravatar for frederik.prijck@auth0.com
By Frederik Prijck

This quickstart demonstrates how to make calls to an external API from a Vue.JS application using Auth0. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Vue 3+

Create an API

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API. You will use the identifier later when you're configuring your Javascript Auth0 application instance. For Signing Algorithm, select RS256.

Create API

Configuring the plugin

To call an API, configure the plugin by setting the audience to the API Identifier of the API you want to call:

import { createAuth0 } from '@auth0/auth0-vue';

const app = createApp(App);

app.use(
  createAuth0({
    domain: "{yourDomain}",
    clientId: "{yourClientId}",
    authorizationParams: {
      redirect_uri: window.location.origin,
      audience: "{yourApiIdentifier}",
    }
  })
);

app.mount('#app');

Was this helpful?

/

Retrieving an Access Token

With the plugin configured using an audience, Auth0 will return an Access Token that can be sent to your API. You can retrieve an Access Token by using the getAccessTokenSilently function thats exposed by our SDK.

<script>
  import { useAuth0 } from '@auth0/auth0-vue';

  export default {
    setup() {
      const { getAccessTokenSilently } = useAuth0();

      return {
        doSomethingWithToken: async () => {
          const token = await getAccessTokenSilently();
        }
      };
    }
  };
</script>

Was this helpful?

/

Using the Options API

If you are using the Options API, you can use the same getAccessTokenSilently method from the global $auth0 property through the this accessor.

<script>
  export default {
    methods: {
      async doSomethingWithToken() {
        const token = await this.$auth0.getAccessTokenSilently();
      }
    }
  };
</script>

Was this helpful?

/

Calling an API

To call an API, include the token in the Authorization header of your request. There are many ways to make HTTP calls with Vue. Here is an example using the fetch API with Vue's Composition API:

<script>
  import { useAuth0 } from '@auth0/auth0-vue';

  export default {
    setup() {
      const { getAccessTokenSilently } = useAuth0();

      return {
        doSomethingWithToken: async () => {
          const token = await getAccessTokenSilently();
          const response = await fetch('https://api.example.com/posts', {
            headers: {
              Authorization: 'Bearer ' + token
            }
          });
          const data = await response.json();
        }
      };
    }
  };
</script>

Was this helpful?

/

Did it work?

Any suggestion or typo?

Edit on GitHub