Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2216,16 +2216,35 @@ 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 { AnonymousSessionError } from '@auth0/auth0-spa-js';

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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
({ accessToken } = await anonymous.getTokenSilently({
audience: 'https://api.example.com'
}));
} else {
throw e;
}
}

await fetch('https://api.example.com/data', {
headers: { Authorization: `Bearer ${accessToken}` }
Expand All @@ -2236,8 +2255,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.
Expand Down
Loading