---
updatedAt: 2026-11-24T23:48:05.000Z
agentTools:
  projectIndex: https://apidocs.taxbit.com/llms.txt
---

# Handling token expiration

Detect and recover from Account Owner token expiration in the SDK.

The SDK doesn't refresh Account Owner tokens automatically — when a token expires during an active session, the SDK's API calls fail with `401 Unauthorized` and surface through your `onError` callback. This page covers how to detect expiration and recover gracefully when it happens.

For the broader auth flow and how to mint tokens, see [Connect your backend](https://apidocs.taxbit.com/docs/integration-guide#connect-your-backend).

# The token model

Your server exchanges your `client_id` + `client_secret` for a tenant-scoped token, then exchanges that for an Account Owner–scoped token. The Account Owner token is the one you pass to the SDK via `bearerToken`. It's valid for **1 hour** (`expires_in: 3600`), unlike the tenant token's 24 hours, so a session that stays open past an hour will hit expiration. See the [token reference](https://apidocs.taxbit.com/reference/post_oauth-account-owner-token). The SDK uses it for every call it makes during the component's lifetime — submission POST, status fetch, prior-submission GET, document URL generation, real-time TIN and GIIN checks, and usage telemetry events. If it expires mid-session, all of those fail until you supply a new one.

# What happens when a token expires

The Taxbit API returns `401 Unauthorized`, and the SDK propagates it through your callbacks:

| Operation                             | Failure surface                                                                                   |
| ------------------------------------- | ------------------------------------------------------------------------------------------------- |
| Initial status fetch on mount         | Shows the error screen (yours, from `config.display.screens.error`, or Taxbit's); `onError` fires |
| Submission POST                       | `onError` fires with the failed request                                                           |
| Document URL generation (`useTaxbit`) | `error` field on the hook is set; `onError` fires if you passed one to it                         |
| Status polling (`useTaxbit`)          | Fetches stop returning fresh data; `error` is set                                                 |
| Usage telemetry                       | Events drop quietly; `onError` doesn't fire and the user isn't affected                           |

A telemetry 401 never reaches `onError`, so it won't trigger your refresh logic or false alarms in monitoring. The next request that does matter, such as a status fetch or the submission, surfaces the expiration.

The error passed to `onError` is a standard `Error` object. Its second argument is the answers the user has entered so far, when there are any. The SDK doesn't parse the status code into a structured shape today — inspect the message, or rely on the fact that an active-session error after mount is almost always a 401.

# Recover after expiration

When `onError` fires with what looks like an expired token, mint a fresh token server-side and pass it to the mounted component. In 7.x the questionnaire uses a new `bearerToken` from its next request, and the user's answers stay:

```jsx
function TaxFormPage() {
  const [bearerToken, setBearerToken] = useState(null);

  const refresh = useCallback(async () => {
    setBearerToken(await mintToken());  // server endpoint that returns a fresh AO token
  }, []);

  // Mint on first render
  useEffect(() => { refresh(); }, [refresh]);

  const handleError = async (err) => {
    if (err.message.includes('401') || isExpiredError(err)) {
      await refresh();                  // same component, new token
      return;
    }
    reportToSentry(err);
  };

  if (!bearerToken) return <Spinner />;

  return (
    <TaxbitQuestionnaire
      bearerToken={bearerToken}
      questionnaire="W-FORM"
      onError={handleError}
      onSuccess={() => router.push('/done')}
    />
  );
}
```

**Don't remount.** Changing the `key` prop, or unmounting the component while you fetch the token, starts the questionnaire over and loses what the user entered. Swap the token on the mounted component.

**Don't clear the token first.** With no token the questionnaire shows "Bearer Token is required", and the next token starts it over. Go straight from the old token to the new one.

**A failed submission stays on screen.** If the 401 came from the submission, the form and answers stay, with "Your Tax Documentation could not be saved. Please try again." above Submit. Once the new token is in, the user presses Submit again.

**An inline `handleError` is fine.** `onError` and `onProgress` fire once per event regardless of the callback's identity, so a handler that sets state doesn't cause a render loop.

**6.x and earlier.** A new `bearerToken` isn't reliably picked up mid-session. Change the `key` prop when you swap tokens to force a remount, so the SDK re-runs its initial status fetch with the new token. The remounted form starts over.

# Best practices

* **Mint server-side, never in the browser.** The `client_secret` exchange must happen on your backend. The browser only ever sees the Account Owner token — narrow by design (one user, short window).
* **Hand the token to the browser just-in-time.** Don't send it at session start and hold it in the browser. Have your client ask your server for the token when the SDK is about to render. Your server returns the cached token while it is still valid and mints a new one only when it is not.
* **Handle 401s explicitly in `onError`.** Distinguish expected expiration (re-mint and continue) from genuine errors (report to monitoring). Both surface through the same callback.
* **Swap the token in place.** In 7.x, pass the new `bearerToken` to the mounted component and leave `key` alone, so the user keeps their answers. On 6.x and earlier, change `key` instead.
* **Keep tokens in memory only in the browser.** Don't persist to client storage. Scope the token to the component or page where the SDK lives; when the tab closes or the user navigates away, the browser's copy is gone. The cache that makes reuse possible lives on your server.
* **Reuse one token across page loads and SDK calls.** The SDK uses a single token for status, submission, and document operations, and the same token stays valid when the user reloads the page or returns within the hour. Requesting a token per page load or per operation adds a round trip your user waits on. Cache the token on your server and request a new one only when it is close to expiring or a `401` arrives. See [Mint an Account Owner token](https://apidocs.taxbit.com/docs/integration-guide#mint-an-account-owner-token).

# Pitfalls

* **Minting on every render or page load.** Use `useEffect` with empty deps for the initial mint and the `onError` handler for refresh — not an unguarded call in the render path. On your server, return the cached token for that Account Owner while it is still valid; don't request a new one each time the page loads.
* **Remounting on refresh in 7.x.** Changing `key`, or rendering a spinner in place of the component while the new token arrives, starts the questionnaire over. Keep the component mounted and pass the new token.
* **Catching 401 only on submit.** The mount-time status fetch fails first. Your `onError` handler has to cover the initial-load case, not just submission.
* **Treating the document URL as long-lived.** `useTaxbit` auto-refreshes it while the bearer is valid; once the bearer expires, the refresh fails. Don't store the URL outside the SDK's render lifecycle.
* **Issuing tokens before step-up auth.** Even a short-lived Account Owner token in the browser is a sensitive credential. If a sensitive area requires 2FA or recent auth, gate the mint endpoint on that — not just session presence.

# Next steps

* [Questionnaire integration guide](https://apidocs.taxbit.com/docs/integration-guide) — the full auth and submission flow
* [Component and hook reference](https://apidocs.taxbit.com/docs/component-and-hook-reference) — `onError`, `bearerToken`, and the `useTaxbit` return values

# Sibling pages

* [How the SDK works](https://apidocs.taxbit.com/docs/how-the-sdk-works.md)
* [Questionnaire integration guide](https://apidocs.taxbit.com/docs/integration-guide.md)
* [Customizing look and feel](https://apidocs.taxbit.com/docs/customizing-look-and-feel.md)
* [Curing integration guide](https://apidocs.taxbit.com/docs/curing-integration-guide.md)
* [Component and hook reference](https://apidocs.taxbit.com/docs/component-and-hook-reference.md)
* [Upgrade guide](https://apidocs.taxbit.com/docs/upgrade-guide.md)

# Sibling pages

* [How the SDK works](https://apidocs.taxbit.com/docs/how-the-sdk-works.md)
* [Questionnaire integration guide](https://apidocs.taxbit.com/docs/integration-guide.md)
* [Customizing look and feel](https://apidocs.taxbit.com/docs/customizing-look-and-feel.md)
* [Curing integration guide](https://apidocs.taxbit.com/docs/curing-integration-guide.md)
* [Component and hook reference](https://apidocs.taxbit.com/docs/component-and-hook-reference.md)
* [Upgrade guide](https://apidocs.taxbit.com/docs/upgrade-guide.md)