useAuthFetch
useAuthFetch() returns an authenticated fetch with the same signature as
the global fetch. It attaches the current access token as a bearer header
and, on a 401, refreshes the session and retries the request once.
The implementation ships from the CDN runtime, so the whole authed transport
(token attach, idempotent-retry, and the 401-refresh-and-retry path)
hot-swaps without an npm bump.
When to use it
Section titled “When to use it”- Calling your own backend from a signed-in component, when you want token
handling done for you (vs. reading a token via
getToken()and wiring the header yourself).
import { useAuthFetch } from '@torii-js/torii-react';import { useEffect, useState } from 'react';
function Orders() { const authFetch = useAuthFetch(); const [orders, setOrders] = useState([]);
useEffect(() => { authFetch('/api/orders') .then((res) => res.json()) .then(setOrders); }, [authFetch]);
return <ul>{orders.map((o) => <li key={o.id}>{o.name}</li>)}</ul>;}Returns
Section titled “Returns”useAuthFetch() throws if called outside a <ToriiProvider>.
| Name | Type | Description |
|---|---|---|
| (return value) | typeof fetch | A fetch-compatible function. Attaches the bearer token, then on a 401 refreshes the session and retries once. Throws if called before the SDK runtime has loaded: gate calls behind isLoaded / isSignedIn from useAuth(), or run them in an effect after sign-in. |
- Same signature as
fetch: pass a URL and optionalRequestInit. When a session token is available, anyAuthorizationheader you set is replaced with the managed bearer; if there is no active token, your header is left as-is. - Two distinct retry paths: on a
401the request is refreshed and reissued once (any method); on a transient network failure (fetch()throws: offline, DNS, CORS, abort) onlyGET/HEADare retried with backoff (~4 attempts online / 11 offline), whilePOST/PUT/PATCH/DELETEare not network-retried so a partial write isn’t applied twice. - For raw token access instead of a wrapped
fetch, usegetToken()(async, refreshes near expiry).