This is the second of two notes on rebuilding session management at MO Marketplace. Part 1 built sessions the server can trust and end. This one is the website, where the browser has its own rules about cookies, origins and tabs.
The general mechanics - why a refresh token belongs in an HttpOnly cookie, and why two refreshes at once look like theft - are in Session Security in Practice. This note covers the decisions the website needed on top of them.
The problem
Part 1 ended with every client receiving its refresh token in the JSON response body. That suits the mobile app, which keeps it in the phone's secure storage. In a browser, anything JavaScript can read, an injected script can read too: an XSS bug, a compromised package or a bad third-party tag. A refresh token is long-lived, so a stolen one is a long-lived session.
Moving it into a cookie is the standard answer. The website added its own constraints on top:
- Shoppers expect to stay signed in. Coming back the next day should not mean logging in again.
- Most visitors are guests. Being signed out is a normal state for a shop, not an error, and the site has to work fully without a session.
- Shoppers open several tabs. Each tab has its own memory, but they all share one cookie, and refresh tokens are single-use.
- A backend outage must not log anyone out. "The server did not answer" is not the same as "the session ended".
The design at a glance
The first half of the work was on the server, because a cookie changes what the server has to check. The second half is the website.
The server: delivering the refresh token by cookie
How the refresh token is delivered became another per-surface setting on the server: the mobile app gets it in the response body, browsers get a cookie. Every login route and the refresh route use one helper for this, so no route has its own delivery logic.
HTTP/1.1 201 Created
Set-Cookie: <name>=<value>; HttpOnly; Secure; SameSite=Strict; Path=<auth>
{ "token": "<access token>", ... }SameSite=Strictprotects refresh and logout from cross-site requests, so those two routes need no separate CSRF token.- The refresh route sits inside the cookie's path. Versioned API routes do not, so the website calls the unversioned refresh route; a versioned one would arrive without the cookie.
- The website can never see the cookie. The only way to find out whether a shopper has one is to call refresh.
The cookie required a real CORS allowlist
Browsers do not send cookies to an API whose CORS setting allows every origin, and this API allowed every origin. So the cookie made a strict allowlist necessary.
The list is in code, one map per environment. Each allowed origin is mapped to the surface it logs into, and the CORS list is the keys of that map:
const ORIGIN_SURFACE: Record<Env, Record<string, Surface>> = {
development: { "<local admin panel>": STAFF, "<local website>": CUSTOMER },
staging: { "<staging admin panel>": STAFF, "<staging website>": CUSTOMER },
production: { "<admin panel>": STAFF, "<website>": CUSTOMER },
};- An origin cannot be allowed without saying which surface it belongs to, because the CORS list comes from the same map.
- The server refuses to start in an environment it has no list for, instead of falling back to a default.
- Origins are compared as exact strings: scheme, host and port, with no trailing slash.
CORS does not stop a request
CORS tells the browser whether a page may read a response. A page from a disallowed origin can still send the request: the handler runs, and the browser hides the response afterwards. For a route that rotates or revokes a session, running the handler is what matters.
There is a second gap. SameSite compares sites, not origins:
Every subdomain of the company's domain counts as the same site, so a page on any of them could make the browser send the refresh cookie. So refresh and logout now check the Origin header before the handler runs:
- An unknown origin is refused with a
403. - A request with a refresh cookie but no
Originis refused. Browsers always send one on these requests. - No origin and no cookie is the mobile app, which sends its refresh token in the body.
This does not stop a command-line client, which can send any Origin it likes, and it is not meant to. A command-line client has no shopper's cookie jar, so it would still need a real token.
Staging and production are also the same site, so SameSite does not keep them apart. Only the origin lists do, and checking that no staging origin is in the production list is part of every release.
One cookie name per surface
A browser stores a cookie under host + path + name. The port and scheme are not part of it, so a different origin does not mean a different cookie. The admin panel and the website call the same API host. With one cookie name, they would share one slot in the browser, and a staff member using both in the same browser would see this:
- Logging in on the website overwrites the admin panel's cookie.
- The admin panel refreshes with the website's token and gets a token for the wrong surface.
- The website then presents a token that has already been rotated. That is exactly what reuse detection looks for, so the whole session is revoked.
The result is random logouts in both apps, and logs that show a theft that never happened. So each surface has its own cookie name, and the refresh route works out the surface from the Origin and reads only that surface's cookie:
- A token from another surface gets a plain
401before anything is written. It is not treated as reuse, because that would let one stale tab end a healthy session. - Logout clears only the caller's cookie. Logging out of the admin panel does not end a shopping session in the same browser.
The name was chosen before any browser held a refresh cookie, so it never had to be renamed. A rename after release would have logged every user out once.
The website: one layer owns the tokens
On the website, screens never touch a token. They see a status and a user, and everything else happens in one layer:
Login, refresh, logout and every private call go straight from the browser to the backend, never through the website's own server. The cookie lives on the backend's host, and the backend identifies the website by the browser's Origin; a hop through the website's server would lose both. The trade-off is that the website's server cannot render logged-in content, such as the shopper's name, in the first HTML. Those parts render in the browser.
The access token stays in memory
The access token lives in a module variable, never in localStorage or sessionStorage, so a script cannot copy a credential that outlives the page. This limits what XSS can do; it does not prevent XSS. A script running in the page can still make calls while it runs.
The cost is that a reload clears it. So every page load starts with one session check:
- If a token is in memory, use it. Otherwise call refresh, and the browser adds the cookie.
- If refresh succeeds, load the current user. If it returns
401, the visitor is a guest.
Until that check settles, the status is loading, so the header does not show "Log in" to a shopper who is logged in. A failed check retries with backoff; an answered one is not repeated until something changes.
Cookies only on the three auth calls
A cross-origin response can only set or replace the session cookie if the request opted in to credentials. fetch already denies this by default: its credentials default is "same-origin", and the website and the API are different origins. So ordinary calls send no cookie, and any Set-Cookie in their responses is ignored.
Only login, refresh and logout pass credentials: "include". The safe setting is the default, so there is no rule to enforce - only three calls that opt in.
One wrapper for private calls
Every call to the backend goes through one request() function, which turns each failure into one of four kinds. The decisions after that are made on the kind:
Private calls go through authFetch(), which wraps request():
- If there is no token yet, it waits for the page-load check instead of sending a call that is sure to fail.
- It attaches the current token when the call is sent, not when it was created.
- On a
401, it refreshes and retries once. If the token already changed while the call was out, because another call refreshed, it skips the refresh and retries with the new token. - A
401from refresh, or a second401on the retry, ends the session. - A
403and every other error is thrown unchanged. A refresh would give the same user the same permissions, so it would fail the same way.
Login and refresh do not go through authFetch(). They call request() directly, so there is no refresh code in their path, and a 401 from refresh cannot start another refresh. That is guaranteed by how the code is built, not by an if that someone could break later. Logout is the exception: it goes through authFetch(), because the server's logout needs a valid access token, and after a shopper has been idle the token is refreshed first.
Refreshing before the token expires
Waiting for a 401 costs a failed call, a refresh and a retry every time the access token expires. So two more pieces sit in the store:
- One refresh at a time in a tab. The in-flight refresh is kept as a promise, and every caller in the tab gets the same one. Any number of
401s, the page-load check and the timer share a single refresh. A tab runs JavaScript on one thread, so this needs no lock inside the tab. - A refresh timer. Each time a token is stored, a timer is set for shortly before it expires, minus a random few seconds. All tabs share one token, and the random offset stops their timers from firing together.
The timer is only there for speed. Background tabs throttle timers and a sleeping laptop runs none, so the 401 path in authFetch() is what keeps sessions correct.
Several tabs, one cookie
Each tab has its own memory: its own token, in-flight refresh and timer. All tabs share one cookie, and every refresh rotates it. If two tabs refresh at the same moment with the same cookie, one wins and the other gets 401 "already used" - which the losing tab reads as a session that has ended:
- A Web Lock around refresh. The refresh runs inside
navigator.locks.request(), so tabs take turns. Inside the lock, a tab first checks whether another tab already stored a fresh token, and if so uses it and skips the call. - A fallback for browsers without Web Locks. If refresh answers "already used", the tab retries once. The winning tab's new cookie is already in the shared cookie jar, so the retry succeeds.
The tabs keep each other in step with a BroadcastChannel. It only reaches tabs of the same origin, and a tab does not receive its own messages:
When a session counts as ended
Logouts spread to every tab, so deciding when a session has ended matters more on the website than anywhere else. Only one answer ends it:
- A
403keeps the session. Logging out cannot fix an origin missing from the allowlist, and it would hide the real problem. - Temporary failures keep it too. Treating "no answer" as "logged out" would log every tab out during a short backend outage.
One function ends every session
A session can end from several places: logout, a 401 from refresh, a 401 after a retry, or another tab logging out. All of them call one function, endSession(), which:
- clears the access token,
- cancels the refresh timer,
- clears the website's stored data, except the guest cart and the last order, which are not tied to the login,
- tells the other tabs, unless the call came from another tab,
- tells the session layer, which clears every cached private response and sets the session to empty.
Because every exit path uses it, none can skip a step. It never calls the backend, so it always works. It does not redirect anywhere either: guests are normal on a shop, so screens simply show the guest state.
Logout itself calls the backend first, so the server revokes the session and clears the cookie (the website cannot delete an HttpOnly cookie itself). endSession() runs after it whether or not the call succeeds, so the screen always logs out.
What screens see
useSession() returns three things:
status:loading,authenticatedorguest.user: the current user, ornull.error:null, atemporaryerror (the backend did not answer; it keeps retrying) or aconfigerror (the backend refused this site's origin).
If the backend is down when a page loads, the status is guest with a temporary error. Nothing is cleared, so the shopper is signed back in automatically when the backend returns. Private screens can use the error to say "can't reach the server" instead of "please log in". Keeping the error separate means every screen still handles only three statuses.
Where it started: the admin panel
The website started from the admin panel's session design and changed it where a shop needs something different. It uses fetch with one wrapper instead of interceptors, and gets safe credentials from fetch's default instead of forcing them off. A lock prevents the refresh race between tabs instead of recovering after it. A 403 from refresh and temporary failures keep the session instead of ending it, and ending a session shows the guest state instead of redirecting to a login page.
Why this mattered
- No page script can read the refresh token. A stolen access token is useful for minutes.
- Shoppers stay signed in across reloads and tabs, and tabs never race each other into a logout.
- Outages do not log anyone out. Only a
401from refresh ends a session; a403or a server that did not answer never does. - The browser rules are enforced on the server: an exact allowlist, an origin check before refresh and logout, and one cookie per surface.
- Mistakes are prevented by design, not by checks: refresh cannot call itself, ordinary calls send no cookie, and one function ends every session.
Together with Part 1, sessions at MO Marketplace can now be trusted, renewed and ended on the server, and the website keeps shoppers signed in without holding a credential that page scripts can read.