How to persist Auth0 login status in browser for React SPA How to persist Auth0 login status in browser for React SPA reactjs reactjs

How to persist Auth0 login status in browser for React SPA


You can use Silent authentication to renew the tokens on browser refresh.

Specifically for your react SPA app

  • setup a state say tokenRenewed to false in your main App component
  • you already have a renewToken method in your auth.js so call that in componentDidMount method
componentDidMount() {   this.auth.renewToken(() => {      this.setState({tokenRenewed : true});   })}
  • update renewToken to accept a callback cb like below
renewSession(cb) {    this.auth0.checkSession({}, (err, authResult) => {      if (authResult && authResult.accessToken && authResult.idToken) {        this.setSession(authResult);      } else if (err) {        this.logout();        console.log(`Could not get a new token. (${err.error}: ${err.error_description})`);      }      if(cb) cb(err, authResult);    });  }
  • Make sure you don't load the App component unless tokenRenewed is true i.e. unless you have the valid tokens renewed via silent authentication
render() {    if(!this.state.tokenRenewed) return "loading...";    return (      // Your App component    );}

Notes:

  1. You may want to make sure you have the correct Allowed Web Origins set in the Application settings for this to work
  2. Silent authentication has some limitations as in it requires 3rd party cookies enabled on the browser and in case ITP for Safari. You should setup a custom domain to avoid that. Refer to the official auth0 docs to learn more here.
  3. More details on how to store token securely here