Authentication
A login form and a profile page backed by the DummyJSON auth API. The token handling lives in two client interceptors, so the requests and components never touch a token.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useEffect, useState } from "react";
import { client, getMe, login, onLog, tokens } from "./api";
const LoginForm = ({ onLogin }: { onLogin: () => void }) => {
const { submit, submitting, error } = useSubmit(login);
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
const { data } = await submit({
payload: {
username: String(form.get("username")),
password: String(form.get("password")),
// A short-lived token, so you can watch it expire and refresh.
expiresInMins: 1,
},
});
if (!data) return;
tokens.set({ accessToken: data.accessToken, refreshToken: data.refreshToken });
onLogin();
};
return (
<article>
<form onSubmit={handleSubmit}>
<label>
Username
<input name="username" defaultValue="emilys" required />
</label>
<label>
Password
<input name="password" type="password" defaultValue="emilyspass" required />
</label>
{error && <p className="error">Login failed: {error.message}</p>}
<button type="submit" aria-busy={submitting} disabled={submitting}>
Log in
</button>
</form>
</article>
);
};
const Profile = ({ onLogout }: { onLogout: () => void }) => {
const { data, error, loading, refetch } = useFetch(getMe);
// Simulates an expired token: the next request gets a 401 and the client refreshes it.
const breakToken = () => {
const current = tokens.get();
if (current) tokens.set({ ...current, accessToken: "expired" });
};
const logout = async () => {
tokens.remove();
// Cached responses belong to the old user, so they go too.
await client.cache.clear();
onLogout();
};
return (
<article aria-busy={loading && !data}>
{error && <p className="error">Could not load the profile: {error.message}</p>}
{data && (
<header className="profile">
<img src={data.image} alt="" width={64} height={64} />
<hgroup>
<h3>
{data.firstName} {data.lastName}
</h3>
<p>
@{data.username} · {data.email}
</p>
</hgroup>
</header>
)}
<div role="group">
<button type="button" onClick={refetch} disabled={loading}>
Reload profile
</button>
<button type="button" className="secondary" onClick={breakToken}>
Expire token
</button>
<button type="button" className="outline" onClick={logout}>
Log out
</button>
</div>
</article>
);
};
const ActivityLog = () => {
const [entries, setEntries] = useState<string[]>([]);
useEffect(() => onLog((message) => setEntries((prev) => [message, ...prev].slice(0, 8))), []);
return (
<article>
<h6>Activity</h6>
{entries.length === 0 && <p className="muted">Nothing yet.</p>}
<ol className="log">
{entries.map((entry, index) => (
<li key={entries.length - index}>{entry}</li>
))}
</ol>
</article>
);
};
export const App = () => {
const [loggedIn, setLoggedIn] = useState(() => tokens.get() !== null);
return (
<main className="container">
<hgroup>
<h1>Authentication</h1>
<p>Log in, then press "Expire token" and "Reload profile" to watch the client refresh the token.</p>
</hgroup>
<div className="grid-2">
{loggedIn ? <Profile onLogout={() => setLoggedIn(false)} /> : <LoginForm onLogin={() => setLoggedIn(true)} />}
<ActivityLog />
</div>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/authentication hyper-fetch-react-authentication && cd hyper-fetch-react-authentication && npm install && npm run devonAuthadds theAuthorizationheader to every request that hasauth: true.onErrorcatches a401, refreshes the token and sends the failed request again.setUsed(true)marks the retried request, so a second401cannot start a refresh loop.- Logout removes the tokens and clears the cache, so the next user never sees the old profile.
How it works
-
api.tsregistersclient.onAuth(). It reads the access token fromlocalStorageand returns a copy of the request with the header set. Requests haveauth: trueby default, sogetMegets the header without any options. -
loginandrefreshsetauth: false. They run before a valid token exists, so the interceptor skips them. -
client.onError()runs for every failed response. On a401it sendsrefreshwith the refresh token, stores the new pair and returns the response of the retried request. That response replaces the401, souseFetch(getMe)only ever sees the profile:tokens.set(data);return request.setUsed(true).send(); -
LoginFormsends the credentials withuseSubmit(login)and asks for a token that expires after one minute. Wait a minute, or press Expire token, then Reload profile: the activity log shows the401, the refresh and the retry. -
Log out removes the tokens and calls
client.cache.clear(), then unmounts the profile.
- APIs that expect a bearer token or an API key header on most requests.
- Short-lived access tokens with a refresh token.
- Apps where several users can log in on the same device.
Related
onAuth attaches the token, onError refreshes it on a 401 and retries once with setUsed(true). Both live on the
client, so every request gets the same behavior.
