diff --git a/EXAMPLES.md b/EXAMPLES.md index 86f6e2dc..4215658c 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -2216,16 +2216,34 @@ Set `createAnonymousSessionOnFailedSilentAuth` on `Auth0Provider` to automatical ### Getting an anonymous access token +The SDK returns a cached token when still fresh and renews it when the access token expires. If the session itself is expired or invalid, `getTokenSilently()` throws an `AnonymousSessionError` — catch it and call `createSession()` to start a new session. + ```jsx -import { useAuth0 } from '@auth0/auth0-react'; +import { useAuth0, AnonymousSessionError } from '@auth0/auth0-react'; function ApiButton() { const { anonymous } = useAuth0(); const callApi = async () => { - const { accessToken } = await anonymous.getTokenSilently({ - audience: 'https://api.example.com' - }); + let accessToken; + try { + ({ accessToken } = await anonymous.getTokenSilently({ + audience: 'https://api.example.com' + })); + } catch (e) { + if ( + e instanceof AnonymousSessionError && + (e.code === 'session_expired' || e.code === 'invalid_session_token') + ) { + // Session is permanently gone. Start a new one and retry. + await anonymous.createSession(); + ({ accessToken } = await anonymous.getTokenSilently({ + audience: 'https://api.example.com' + })); + } else { + throw e; + } + } await fetch('https://api.example.com/data', { headers: { Authorization: `Bearer ${accessToken}` } @@ -2236,8 +2254,6 @@ function ApiButton() { } ``` -The SDK returns a cached token when still fresh and renews it transparently when expired. - ### Explicit anonymous session creation with metadata Call `anonymous.createSession()` directly to attach metadata at creation time.