An SPA (Single Page Application, for example one built with React or Vue) and a mobile app both have to keep the login mark on the client. The question is where, so it stays safe without making the user log in again and again. Picture a boarding house. localStorage is a key hanging on the living-room wall: anyone who walks in can take it, strangers included. JavaScript memory is a key in your pocket: safe, but gone the moment you change clothes. An HttpOnly cookie is a key the caretaker holds: he opens the door for you every time, but never hands the key over. In this picture, the key is the token, the house is your page, the people who walk in are scripts, changing clothes is a reload, and the caretaker is the browser, which sends the token with every request. On a phone, the Keychain (iOS) and Keystore (Android) are a private safe belonging to one app.
Three places to keep a token in the browser
| Place | Readable by scripts on the page? | Survives a reload? | Sent automatically? |
|---|---|---|---|
localStorage |
yes, any script | yes, until removed | no |
| Memory (a variable) | only the code holding the variable | no | no |
HttpOnly cookie |
not at all | yes, until it expires | yes, to its domain |
"Scripts on the page" include third-party scripts (JavaScript loaded from someone else's server) and any script that gets in through an XSS hole. Any script on the page can read and copy a token in localStorage at any time, and the copy stays valid until that token expires. A token in memory is gone when the tab closes, so after that there is nothing to take. An HttpOnly cookie is invisible to document.cookie (the way JavaScript reads cookies). But because the browser sends it automatically, the endpoints that use that cookie need CSRF protection (the next lesson, CSRF Protection). The full comparison is in Secure Storage in the Browser in the Security track.
School Portal's pattern: memory + an HttpOnly cookie
Exactly as in Token Refresh Flow: a 15-minute access token in memory, a 30-day refresh token in an HttpOnly cookie. The access token lives in a closure: the variable accessToken is created inside createTokenStore, and only the methods that function returns can read it.
function createTokenStore() {
let accessToken = null; // in a closure: not in localStorage, gone on reload
return {
setAccessToken(token) { accessToken = token; }, // { value, expiresAt } in milliseconds
getAccessToken() { return accessToken; },
clearTokens() { accessToken = null; },
isAuthenticated() { return accessToken !== null && accessToken.expiresAt > Date.now(); },
needsRefresh(token) { return token.expiresAt - Date.now() < 60000; }, // under 60 seconds left
};
}
Siti logs in at 07:00:00, and token A1 expires at 07:15:00 (expiresAt 1791504900000, in milliseconds). This is what the last two methods answer at a few times:
| Time | isAuthenticated() |
needsRefresh(token) |
What the app does |
|---|---|---|---|
| before login | false |
show the login form | |
| 07:00:00 | true |
false, 900,000 ms left |
call the API as usual |
| 07:14:30 | true |
true, 30,000 ms left |
refresh first, then call the API |
| 07:15:00 | false |
true |
the token has expired: refresh |
accessToken !== null && ...returns a boolean. Written asaccessToken && ..., it givesnullbefore login, notfalse.needsRefreshcompares milliseconds: 60 seconds = 60000. The app refreshes when the token has less than 60 seconds left, before it expires. So a request is never refused with a401because its token has expired.
Reload: memory empty, the cookie still there
Siti presses reload. Does she have to log in again, or does she stay in? A reload empties every variable, so A1 is gone. But the refresh_token cookie is still in the browser. As soon as the app loads, initAuth calls /auth/refresh once:
const store = createTokenStore();
async function initAuth() {
const res = await fetch("/auth/refresh", { method: "POST", credentials: "include" }); // the cookie goes along by itself
if (!res.ok) return false; // not logged in, or the refresh token is over
const { access_token, expires_in } = await res.json();
store.setAccessToken({ value: access_token, expiresAt: Date.now() + expires_in * 1000 });
return true;
}
The server answers with a new access token A2, and Siti stays in without ever seeing the login form.
Laravel Sanctum: a session cookie or an API token
Laravel Sanctum has two modes:
SPA mode (a session cookie), for your own SPA on the same domain as its API. For example, the SPA is at portal.school.test and the API at api.school.test: both are under school.test. The SPA holds no token at all. Sanctum uses Laravel's ordinary session, as in the Session-based Authentication lesson. These are the settings on the server:
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {
$middleware->statefulApi(); // requests from stateful domains use the session cookie
})
// .env
// SANCTUM_STATEFUL_DOMAINS=portal.school.test
// SESSION_DOMAIN=.school.test
Then in the SPA, the JavaScript uses axios (a library for sending requests):
axios.defaults.withCredentials = true; // send cookies to api.school.test
axios.defaults.withXSRFToken = true; // copy the XSRF-TOKEN cookie into the X-XSRF-TOKEN header
await axios.get("https://api.school.test/sanctum/csrf-cookie"); // 204, sets the XSRF-TOKEN cookie
await axios.post("https://api.school.test/login", { email: "[email protected]", password: "secret123" });
const { data } = await axios.get("https://api.school.test/api/user"); // { id: 1, name: "Siti", ... }
/sanctum/csrf-cookieanswers204and sets two cookies. The first isXSRF-TOKEN, which holds the CSRF token and which JavaScript is meant to read. The second is theHttpOnlysession cookieschool_portal_session.- After login, the session cookie goes along with every request. API routes are protected with
->middleware('auth:sanctum'). The SPA and the API are still different origins, so in the CORS config (the permission for JavaScript from another origin),supports_credentialsmust betrue.
API token mode, for mobile apps and third-party clients (apps made by others). $user->createToken('Siti phone')->plainTextToken gives a string like 1|k3J9.... The database stores only its SHA-256 hash. The client sends that string in the Authorization: Bearer header, and $token->delete() revokes it.
BFF: tokens stay on the server
When an SPA must log in through OAuth (say, the school's Google accounts), the pattern is a BFF (Backend for Frontend): a small server dedicated to one frontend. The BFF runs the OAuth flow, then keeps the access and refresh tokens in its session on the server. The SPA holds only an HttpOnly session cookie for the BFF, and the BFF attaches tokens to API requests. So tokens never reach JavaScript. Sanctum's SPA mode is really a simple form of this idea: your own API is also the BFF.
Mobile apps: no client_secret, keep it in the Keychain or Keystore
A mobile app is a public client: its file (an APK or IPA, the install file for Android or iOS) sits on everyone's phone and can be taken apart. So anyone can find any client_secret built into it. That's why OAuth login from a mobile app uses PKCE with no client_secret: for each login, the app makes a random code_verifier and sends its code_challenge (the steps are in OAuth 2.0 Flow). Three more rules:
- Open the login page in the system browser (the phone's own browser, opened through ASWebAuthenticationSession on iOS or Custom Tabs on Android), not in a WebView (a small browser built into the app). In a WebView, the app can read what the user types.
- After login, the user is sent back to the app through a registered URI. The best choice is an
httpslink on your domain that the app claims (a Universal Link on iOS, an App Link on Android), such ashttps://portal.school.test/callback. The reason: the OS (the phone's operating system) checks that a file on that domain names your app. If you use a custom scheme (a URI prefix you make up yourself, instead of https), its name must be a domain you own written in reverse, such astest.school.portal:/callback(RFC 8252), so it doesn't clash with another app's scheme. Another app can still register the same scheme, so PKCE is still required. - Keep the refresh token or Sanctum token in the Keychain (iOS) or Keystore (Android), for example through the library
expo-secure-storeorflutter_secure_storage. Not in AsyncStorage or plain SharedPreferences (the ordinary storage of React Native and Android), whose contents are not encrypted.
⚠️ Wrong place, wrong unit, wrong mode
- A token in
localStorage. Any script on the page can read it. Keep the access token in memory, and let theHttpOnlycookie be the part that lasts after a reload. isAuthenticatedreturningnull.accessToken && ...givesnullbefore login. WriteaccessToken !== null && ....- A refresh threshold in seconds.
expiresAt - Date.now() < 60means 60 milliseconds left, not 60 seconds. Write60000. - Sanctum's SPA mode on another site.
school-portal.comandapi.school.testare not under the same domain, so they are different sites. A session cookie withSameSite=Laxdoesn't go along on requests fromschool-portal.comtoapi.school.test. For another site or a mobile app, use API tokens. - A
client_secretin a mobile app. The app can be taken apart, so it is no secret any more. Use PKCE.
TL;DR: In an SPA (a web app that runs fully in the browser), keep the access token in memory (a variable inside a closure, as in createTokenStore) and the refresh token in an HttpOnly cookie, which JavaScript cannot read. Not in localStorage, which any script can read. isAuthenticated() = accessToken !== null && accessToken.expiresAt > Date.now(), and needsRefresh(token) = less than 60000 ms (60 seconds) of the token's life left. On reload, memory is empty but the cookie is still there, so the app calls /auth/refresh and the user stays in. Laravel Sanctum has two modes. SPA mode uses a session cookie (/sanctum/csrf-cookie, statefulApi(), an XSRF-TOKEN cookie for the CSRF token) for an SPA on the same domain as its API. API token mode (createToken, Bearer) is for mobile apps. A BFF (a small server dedicated to one frontend) keeps OAuth tokens on the server and gives the SPA only a session cookie. A mobile app is a public client (its file can be taken apart): no client_secret, use PKCE, log in through the system browser, and keep tokens in the Keychain or Keystore, the phone's safe for one app.
⚡ Three places to keep a token
Meaning: Picture the token as a key, your page as a boarding house, and each script on the page as a person who walks into it. localStorage is a key hanging on the living-room wall: any script on the page can take it, including one that got in through an XSS hole. Memory (a JavaScript variable) is a key in your pocket: safe, but gone on reload. An HttpOnly cookie is held by the browser, like a key the caretaker holds: scripts can't read it, but the browser sends it by itself with every request. School Portal keeps the access token in memory and the refresh token in an HttpOnly cookie.
⚡ The access token in a closure
Write:
function createTokenStore() {
let accessToken = null; // in a closure: not in localStorage, gone on reload
return {
setAccessToken(token) { accessToken = token; }, // { value, expiresAt } in milliseconds
getAccessToken() { return accessToken; },
clearTokens() { accessToken = null; },
isAuthenticated() { return accessToken !== null && accessToken.expiresAt > Date.now(); },
needsRefresh(token) { return token.expiresAt - Date.now() < 60000; }, // under 60 seconds left
};
}
Meaning: createTokenStore keeps the access token in the variable accessToken inside a closure: only the methods this function returns can read it. isAuthenticated() uses !== null so the result is always a boolean, never null. needsRefresh compares milliseconds: 60 seconds = 60000. The app refreshes before the token expires, so a request is never refused with a 401 because its token has expired.
⚡ Reload: memory empty, the cookie still there
Guess first: Siti's access token is in memory, and her refresh token is in an HttpOnly cookie. Siti presses reload. Does she have to log in again?
No. A reload empties every variable, so the access token is gone. But the refresh_token cookie is still in the browser, so the app calls /auth/refresh once and gets a new access token.
Meaning: Unlike an SPA, a mobile app is a public client: its file sits on everyone's phone and can be taken apart, so any client_secret inside it can be found. Use PKCE (from OAuth 2.0 Flow), open the login in the system browser (the phone's own browser), and keep tokens in the Keychain (iOS) or Keystore (Android), a safe owned by one app.