Frontend Authentication
Decide where the credential lives, and be honest about what the client is allowed to enforce.
In this chapter: the three places a credential can sit · silent refresh and the thundering herd · guarding routes without lying · multi-tab logout · what the client may never enforce
💡 The Core Idea
Two sentences carry most of a frontend auth design.
The browser has no safe place to put a credential. It only has places that fail in different ways. Memory dies on refresh. localStorage is readable by any script that gets injected. An httpOnly cookie is hidden from your own code but travels on requests you did not start. Choosing between those failures is the design, and everything else follows from it.
Nothing the client does is enforcement. A route guard, a hidden button and a permission check are all user interface. They make the product consistent, but they stop nobody. The server re-checks every one of them, or the check does not exist. A candidate who says this unprompted has largely passed the auth portion of the round.
The protocol side (session design, token issuance and OAuth flows) is covered in Credentials, Sessions, CORS and CSRF and OAuth, OIDC and Authorisation. This chapter is the browser's half.
How It Works
| Where the credential sits | Survives | Exposed to | Use when |
|---|---|---|---|
| JavaScript memory | Nothing — gone on refresh | Only running code | Short-lived access tokens |
localStorage | Refresh, restart, other tabs | Any injected script | Almost never |
httpOnly, Secure, SameSite cookie | Refresh, restart, other tabs | Sent automatically on matching requests | The long-lived credential |
The pattern this table points at is a short-lived access token in memory, with a long-lived refresh token in an httpOnly cookie. Cross-site scripting (XSS) cannot read the cookie, and it finds no token sitting in storage. An injected script can still act as the user while the page is open. Cross-site request forgery (CSRF) cannot use the access token, because it lives in an Authorization header a forged form cannot set.
Silent refresh. The user never sees the 401, and the long-lived credential never passes through JavaScript.
⚠️
SameSiteis not a CSRF strategy on its own.SameSite=Laxstill permits top-levelGETnavigations, so any state change reachable by aGETis still forgeable. Keep changes on methods such asPOST, and pair the cookie with a token check. See Credentials, Sessions, CORS and CSRF.
When to Use It
The token-in-memory pattern is the default, not the only answer.
| The application | Credential design | Why |
|---|---|---|
| A single-page app against your own API | Access token in memory, refresh in a cookie | XSS cannot read it and CSRF cannot use it |
| A server-rendered app, same origin | Plain session cookie, no token in the client | Simpler, instantly revocable, and there is no client to steal from |
| A mobile or native client | Platform secure storage, not the web pattern | The browser's constraints do not apply |
| A public API consumed by third parties | OAuth with per-client tokens | You are not the only client, so session semantics do not fit |
The second row is the one candidates under-use. If the application already renders on the server, adding tokens buys nothing and costs you revocation. The server can delete a session, but it cannot take back a token.
Silent Refresh Without a Stampede
The interesting problem is concurrency. A dashboard fires eight requests, the token expires, and eight 401s arrive at once. A naive interceptor starts eight refreshes, and they race. With refresh-token rotation, the first one wins, the other seven get rejected, and the user is logged out.
Single-flight refresh — every caller awaits the same promise:
let token: string | null = null;
let inFlight: Promise<string> | null = null;
function refresh(): Promise<string> {
// ✅ One refresh in flight; concurrent callers join it instead of starting another.
inFlight ??= fetch("/auth/refresh", { method: "POST", credentials: "include" })
.then((res) => {
if (!res.ok) throw new Error("refresh failed");
return res.json() as Promise<{ accessToken: string }>;
})
.then(({ accessToken }) => accessToken)
.finally(() => { inFlight = null; });
return inFlight;
}
async function authedFetch(input: RequestInfo, init: RequestInit = {}): Promise<Response> {
const res = await fetch(input, withToken(init, token));
if (res.status !== 401) return res;
token = await refresh();
return fetch(input, withToken(init, token)); // retried exactly once
}Three details matter. The promise is shared, so concurrent 401s collapse into one refresh. The retry happens once. Retrying a second 401 is an infinite loop against an expired session. And finally clears inFlight, so a failed refresh does not hand every later request a rejected promise.
A timer that refreshes just before expiry is a useful extra, but it does not replace this. A laptop that slept through the expiry wakes with a dead token and needs the 401 path anyway.
Guarding Routes Without Lying
Authentication has three states. Designs that model only two produce the two worst bugs in this area.
| State | The UI shows | The bug when this state is missing |
|---|---|---|
| Unknown | A skeleton, no redirect | Every refresh bounces the user to the login page |
| Authenticated | The route | — |
| Anonymous | A redirect, preserving the destination | The user logs in and lands on the home page |
On first load the client does not yet know who the user is, because it has not yet exchanged the refresh cookie. Treating that as "anonymous" logs the user out on every hard refresh. Treating it as "authenticated" flashes protected content before the redirect.
Keep the intended destination through the login round trip, and validate it before redirecting back. An unvalidated returnTo parameter is an open redirect. Every penetration test that looks for one reports it.
Multi-Tab and Logout
The access token lives in memory, so every tab holds its own copy. Logging out in one leaves the others showing a signed-in interface for a session that no longer exists.
Telling the other tabs:
const channel = new BroadcastChannel("auth");
export function logout(): void {
token = null;
channel.postMessage({ type: "logout" }); // ✅ other tabs drop their copy immediately
void fetch("/auth/logout", { method: "POST", credentials: "include" });
}
channel.onmessage = (event: MessageEvent<{ type: string }>) => {
if (event.data.type === "logout") token = null;
};This is a user-experience fix, not a security control. The session is dead on the server the moment the cookie is cleared. A tab that missed the broadcast fails on its next request anyway. The message only stops it showing stale data until then. The same channel helps in the opposite case. A tab that refreshes can share the new token, so the others do not each trigger their own 401.
Common Mistakes
❌ Tokens in localStorage. One injected script reads every credential on the origin. ✅ Access token in memory, refresh token in an httpOnly cookie.
❌ Concurrent refreshes. Eight 401s start eight refreshes and rotation logs the user out. ✅ Single-flight the refresh and have every caller await the same promise.
❌ Hiding a control instead of blocking the action. The button is gone; the endpoint is not. ✅ Re-check every permission on the server. The client's copy is presentation.
❌ No "unknown" auth state. Either a bounce to login on every refresh, or a flash of protected content. ✅ Model three states and render a skeleton until the session resolves.
❌ Redirecting to an unvalidated returnTo. An open redirect, used for convincing phishing. ✅ Allow only same-origin relative paths from a known set.
❌ Assuming logout in one tab logs out the others. Five tabs keep working with a revoked session. ✅ Broadcast the change across tabs, and let the next 401 finish the job.
🔑 Key Takeaways
- The browser has no safe credential store, only stores that fail differently; pick the failure you can live with.
- A short-lived access token in memory plus an
httpOnlyrefresh cookie keeps both out of reach of XSS theft and CSRF. - Refresh must be single-flight and retried exactly once, or token rotation turns a burst of 401s into a logout.
- Authentication has three states, and omitting "unknown" causes either a login bounce or a flash of protected content.
- Route guards and hidden buttons are user interface, and the server enforces every rule, without exception.
Interview Questions
Q: Where do you store the token, and why not localStorage?
The access token goes in a module-scoped variable and the refresh token in an httpOnly, Secure, SameSite cookie. Any script that runs on the origin can read localStorage. So one injected script, from a dependency or a tag manager, can steal every session. The cookie is hidden from JavaScript. The access token travels in an Authorization header, not automatically, so a forged cross-site request cannot use it either.
Q: Eight requests get a 401 at the same moment. What happens?
One refresh. The interceptor holds a single in-flight promise, and callers that arrive during it await the same one instead of starting their own. Without that, eight refreshes race. With refresh-token rotation, the first one invalidates the token the other seven are using, so the user's own dashboard logs them out. Each request retries exactly once after the refresh resolves. A second 401 is a real failure and goes to login.
Q: The client hides the delete button for non-admins. Is that authorisation?
No, it is layout. It keeps an admin-only action out of the interface, which is worth doing. But anyone can reach the endpoint from a terminal, and the role claim in a token is data the client can see. Authorisation is the server's check on every request. I would treat the client's permission map as a copy of the policy for rendering, and never as the policy.
Q: When would you not use tokens at all?
When the application is server-rendered on one origin. A plain session cookie is simpler and gives the client nothing to leak. The part that usually decides it: you can revoke it at once, because deleting the session row ends it. You cannot take back a token. You either wait out its lifetime or build the denylist that stateless tokens were meant to avoid. I would only reach for tokens when several clients or origins are involved.
What to Read Next
- Credentials, Sessions, CORS and CSRF — the server's half: issuance, rotation and revocation
- OAuth, OIDC and Authorisation — where permissions are actually enforced, and how the model is designed
- XSS Prevention and Untrusted Input — the attack the whole storage argument above is defending against