Docs

Auth0 Single Page App SDK

The Auth0 Single Page App SDK is a new JavaScript library for implementing authentication & authorization in single page apps (SPA) with Auth0. It provides a high-level API and handles a lot of the details so you can secure SPAs using best practices while writing less code.

The Auth0 SPA SDK handles grant and protocol details, token expiration and renewal, as well as token storage and cacheing. Under the hood, it implements Universal Login and the Authorization Code Grant Flow with PKCE.

The library is hosted on GitHub and you can find the API documentation here.

If you're planning on migrating a SPA that uses auth0.js to the Auth0 SPA SDK, check out Migrate from Auth0.js to the Auth0 Single Page App SDK for examples.

If you encounter some problems or errors when using the new JavaScript SDK, please check out the FAQ to see if your issue is covered there.

Installation

You have a few options for using auth0-spa-js in your project:

From the CDN:

<script src="https://cdn.auth0.com/js/auth0-spa-js/1.2/auth0-spa-js.production.js"></script>

Using npm:

npm install @auth0/auth0-spa-js

Using yarn:

yarn add @auth0/auth0-spa-js

If you use NPM or Yarn to install auth0-spa-js, don't forget to import the package to your project: import auth0-spa-js from 'auth0-spa-js'.

Getting Started

Create the client

First, you'll need to create a new instance of Auth0Client client object. Create the Auth0Client instance before rendering or initializing your application. You can do this using either the async/await method, or with promises. You should only create one instance of the client.

// either with async/await
const auth0 = await createAuth0Client({
  domain: 'YOUR_DOMAIN',
  client_id: 'YOUR_CLIENT_ID'
});
// or with promises
createAuth0Client({
  domain: 'YOUR_DOMAIN',
  client_id: 'YOUR_CLIENT_ID'
}).then(auth0 => {
  //...
});

Login and get user info

Next, create a button users can click to start logging in.

<button id="login">Click to Login</button>

Listen for click events on the button you created. When the event occurs, use the desired login method to authenticate the user (loginWithPopup() in this example). After the user is authenticated, you can retrieve the user profile with the getUser() method.

// either with async/await
document.getElementById('login').addEventListener('click', async () => {
  await auth0.loginWithRedirect({
    redirect_uri: 'http://localhost:3000/'
  });
  //logged in. you can get the user profile like this:
  const user = await auth0.getUser();
  console.log(user);
});
// or with promises
document.getElementById('login').addEventListener('click', () => {
  auth0.loginWithRedirect({
    redirect_uri: 'http://localhost:3000/'
  }).then(token => {
    //logged in. you can get the user profile like this:
    auth0.getUser().then(user => {
      console.log(user);
    });
  });
});

Call an API

To call your API, start by getting the user's Access Token. Then use the Access Token in your request. In this example the getTokenSilently method is used to retrieve the Access Token.

<button id="callApi">Call an API</button>
// either with async/await
document.getElementById('callApi').addEventListener('click', async () => {
  const accessToken = await auth0.getTokenSilently();
  const result = await fetch('https://exampleco.com/api', {
    method: 'GET',
    headers: {
      Authorization: 'Bearer ' + accessToken
    }
  });
  const data = await result.json();
  console.log(data);
});
// or with promises
document.getElementById('callApi').addEventListener('click', () => {
  auth0
    .getTokenSilently()
    .then(accessToken =>
      fetch('https://exampleco.com/api', {
        method: 'GET',
        headers: {
          Authorization: 'Bearer ' + accessToken
        }
      })
    )
    .then(result => result.json())
    .then(data => {
      console.log(data);
    });
});

Logout

Finally, add a button users can click to logout.

<button id="logout">Logout</button>
document.getElementById('logout').addEventListener('click', () => {
  auth0.logout();
});

Usage

Below are examples of usage for various methods in the SDK. Note that jQuery is used in these examples.

Login with popup

$('#loginPopup').click(async () => {
  await auth0.loginWithPopup();
});

Login with redirect

$('#loginRedirect').click(async () => {
  await auth0.loginWithRedirect({
    redirect_uri: 'http://localhost:3000/'
  });
});

Redirect to the /authorize endpoint at Auth0, starting the Universal Login flow.

Login with redirect callback

$('#loginRedirectCallback').click(async () => {
  await auth0.handleRedirectCallback();
});

Get Access Token with no interaction

$('#getToken').click(async () => {
  const token = await auth0.getTokenSilently();
});

The getTokenSilently() method requires you to have Allow Skipping User Consent enabled in your API Settings in the Dashboard. Additionally, user consent cannot be skipped on 'localhost'.

Get Access Token with popup

$('#getTokenPopup').click(async () => {
  const token = await auth0.getTokenWithPopup({
    audience: 'https://mydomain/api/',
    scope: 'read:rules'
  });
});

Get Access Token for a different audience

$('#getToken_audience').click(async () => {
  const differentAudienceOptions = {
    audience: 'https://mydomain/another-api/',
    scope: 'read:rules',
    redirect_uri: 'http://localhost:3000/callback.html'
  };
  const token = await auth0.getTokenSilently(differentAudienceOptions);
});

Get user

$('#getUser').click(async () => {
  const user = await auth0.getUser();
});

Get ID Token claims

$('#getIdTokenClaims').click(async () => {
  const claims = await auth0.getIdTokenClaims();
  // if you need the raw id_token, you can access it
  // using the __raw property
  const id_token = claims.__raw;
});

Logout (default)

$('#logout').click(async () => {
  auth0.logout({
    returnTo: 'http://localhost:3000/'
  });
});

Logout with no client ID

$('#logoutNoClientId').click(async () => {
  auth0.logout({
    client_id: null,
    returnTo: 'http://localhost:3000/'
  });
});