We are excited to announce the release of our new JavaScript SDK for Single Page Applications (SPAs) called auth0-spa-js.
Why a New SDK?
The
library has been our default browser-based SDK for the last few years and has been a key part of our product and success. It has over 100K+ weekly downloads and is used by almost every Auth0 customer in one way or the other.auth0.js
Over this time, we have developed a large set of capabilities in the core product. As the platform has moved forward,
auth0.js
has grown in size and capabilities. While auth0.js
is an extremely powerful SDK that can handle a large number of different scenarios, this versatility comes at a price.We went back to the drawing board and we re-imagined how a web platform SDK should work for the most common scenarios developers will be implementing. This new SDK:
- integrates with Universal Login, our flagship login experience
- is much easier to integrate into Single Page Apps and requires less code
- abstracts the developer from standards and protocols
- frees the developer from having to specify the grant or other protocol details, manage token expiration and renewal, or store and cache tokens
- follows industry and service best practices and protects developers from security pitfalls
- weights around 7kb minified and gzipped
We're excited about these changes and hope our customers and developer community find this new SDK easy to use yet still powerful and secure.
“.@auth0 has a new SDK to keep SPAs secure called auth0-spa-js. Check it out!”
Tweet This
When to Use auth0-spa-js
(and When Not to)
auth0-spa-js
The new SDK is designed for use in SPAs to keep them secured using industry best practices.
The OAuth2 working group has published a new general best current practices document for using OAuth2 to invoke APIs from Single Page Applications. The recommendation is now to use the authorization code grant with Proof Key for Code Exchange (PKCE), as opposed to using the implicit grant as described in the original OAuth2 spec. You can find more details in this blog post from our Principal Architect Vittorio Bertocci.
This new JavaScript SDK implements the authorization code grant with PKCE for authentication, so by using this new library, you will be following the latest industry best practices when it comes to security in Single Page Applications.
Don't worry, we will not be discontinuing support of
auth0.js
. In fact, if you still use embedded login or need to call the management API or authentication API, you'll want to stick with auth0.js
. We encourage you to switch to auth0-spa-js
if you're using Universal Login in a SPA.How to Use Auth0 SPA JS SDK
So how do you start using the new SDK? Here are some steps for vanilla JavaScript that can then be applied to the framework of your choice.
Installation
To use the new SDK, first install it from npm:
npm install @auth0/auth0-spa-js
Alternatively, you can include it in your project using our CDN:
<script src="https://cdn.auth0.com/js/auth0-spa-js/1.0/auth0-spa-js.production.js"></script>
Create the client
Once
auth0-spa-js
is added to your project, you'll need to create an instance of the Auth0 client in your application. Ideally, you should have only one instance of the client. Do this before rendering or initializing your application.You can do this using async/await:
//with async/await const auth0 = await createAuth0Client({ domain: '<AUTH0_DOMAIN>', client_id: '<AUTH0_CLIENT_ID>' });
Or with promises:
//with promises createAuth0Client({ domain: '<AUTH0_DOMAIN>', client_id: '<AUTH0_CLIENT_ID>' }).then(auth0 => { //... });
Logging in
Adding the ability to log in to your application is easy. Given the following button:
<button id="login">Click to Log In</button>
You can add a click handler and then call the
method:loginWithRedirect()
document.getElementById('login').addEventListener('click', () => { return auth0.loginWithRedirect(); });
Once the user is redirected back to the app after authenticating with Auth0, your app will need to call
: handleRedirectCallback()
await auth0.handleRedirectCallback();
This is what parses the result from Auth0, stores the tokens, and sets up the session. You'll then be able to get the user or token as needed:
const user = await auth0.getUser(); const token = await auth0.getTokenSilently();
Calling an API
You can also use the SDK to silently get a token and then use that token in a call to an API.
Given the following button:
<button id="call-api">Call an API</button>
You'll add a click handler, call
, and then use the returned token in your API call.getTokenSilently()
Here it is with async/await:
//with async/await document.getElementById('call-api').addEventListener('click', async () => { const accessToken = await auth0.getTokenSilently(); const result = await fetch('https://myapi.com', { method: 'GET', headers: { Authorization: `Bearer ${accessToken}` } }); const data = await result.json(); console.log(data); });
And with promises:
//with promises document.getElementById('call-api').addEventListener('click', () => { auth0 .getTokenSilently() .then(accessToken => fetch('https://myapi.com', { method: 'GET', headers: { Authorization: `Bearer ${accessToken}` } }) ) .then(result => result.json()) .then(data => { console.log(data); }); });
If there's a valid token stored,
getTokenSilently
will return it. Otherwise, it opens an iframe with the /authorize
URL using the parameters provided as arguments and returns the token.Logging out
Finally, logging out of your application is a matter of adding an event handler to your log out button and then calling Auth0's
method.logout()
Here's the button:
<button id="logout">Log Out</button>
And here is the click handler and the call to
logout()
:document.getElementById('logout').addEventListener('click', () => { auth0.logout(); });
Behind the Curtain
Since many developers (myself included) are wary of black boxes, let's take a moment to look at the protocols behind the new SDK.
While our intent is to abstract away all the implementation details in this new SDK so you don't need to worry about them, identity geeks will be pleased to know that
auth0-spa-js
is compliant with OAuth 2.0 specifications:
uses authorization code with PKCEloginWithRedirect
uses authorization code with PKCE +loginWithPopup
web_message
uses authorization code with PKCE +getTokenSilently
web_message
Auth0 takes our commitment to security best practices seriously. Luckily, we do all the heavy lifting so you don't have to!
Where to Go Next
To learn more about using
auth0-spa-js
, check out the Auth0 Single Page Applications SDK introduction documentation, repository, and the SDK's full documentation. There are also Quickstarts that will walk you through integration step-by-step for popular front-end frameworks like React and Angular. We hope you're as excited about this new SDK as we are, and look forward to hearing feedback from the developer community!About Auth0
Auth0 by Okta takes a modern approach to customer identity and enables organizations to provide secure access to any application, for any user. Auth0 is a highly customizable platform that is as simple as development teams want, and as flexible as they need. Safeguarding billions of login transactions each month, Auth0 delivers convenience, privacy, and security so customers can focus on innovation. For more information, visit https://auth0.com.