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
tofalse
in your main App component - you already have a
renewToken
method in yourauth.js
so call that incomponentDidMount
method
componentDidMount() { this.auth.renewToken(() => { this.setState({tokenRenewed : true}); })}
- update
renewToken
to accept a callbackcb
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
istrue
i.e. unless you have the valid tokens renewed via silent authentication
render() { if(!this.state.tokenRenewed) return "loading..."; return ( // Your App component );}
Notes:
- You may want to make sure you have the correct
Allowed Web Origins
set in the Application settings for this to work - 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.
- More details on how to store token securely here