Skip to content
Torii docs

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.

  • 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>;
}

useAuthFetch() throws if called outside a <ToriiProvider>.

NameTypeDescription
(return value)typeof fetchA 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 optional RequestInit. When a session token is available, any Authorization header 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 401 the request is refreshed and reissued once (any method); on a transient network failure (fetch() throws: offline, DNS, CORS, abort) only GET/HEAD are retried with backoff (~4 attempts online / 11 offline), while POST/PUT/PATCH/DELETE are not network-retried so a partial write isn’t applied twice.
  • For raw token access instead of a wrapped fetch, use getToken() (async, refreshes near expiry).