Note: There are multiple ways of implementing login. The example above displays the Lock Widget. However you may implement your own login UI by changing the line <script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script> to <script src="https://cdn.auth0.com/w2/auth0-7.4.min.js"></script>.

3. Make Secure Calls to an API

To make secure calls to an API, attach the user's JWT as an Authorization header to the HTTP request. This is done in the RequestInit object as the second argument to the fetch call.

You can then remove the RequestInit object (the second argument of fetch) from individual HTTP calls.

5. Optional: Decode the User's JWT to Check Expiry

Checking whether the user's JWT has expired is useful for conditionally showing or hiding elements and limiting access to certain routes. This can be done with the jwt-decode package and a simple function. First, install the package.

npm install jwt-decode --save

Next, we can create a utilities file that will have a function that decodes the JWT and checks whether it has expired.

This hook will redirect the user to some other route (public in this case) if the user's JWT has expired.

Persisting Application State

Lock uses redirect mode by default, meaning that a full page refresh will occur when users go through the authentication process in your application. This can be undesirable in single page apps, especially if the application contains state that should be displayed to the user again after they authenticate. For example, it may be the case that your users can initiate authentication from an arbitrary route within your single page app and you may want to return them to that location (along with any relevant state) after authentication is complete.

The recommended solution for this is to persist any necessary application state in local storage or a cookie before the user logs in or signs up. With this data, you can provide some custom post-authentication logic in the listener for the authenticated event to allow the user to pick up from where they left off.

In cases where storing application state is not possible, Lock's popup mode can be used. Please note that popup mode is not recommended. Known bugs in certain browsers prevent popup mode from functioning as expected under some circumstances.