Sessions vs tokens in a SPA
Pick between a server-side session cookie and a signed token for a SPA: what each stores, what logout means, and what an XSS bug costs you.
Sessions vs tokens in a SPA
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A session stores the login state on the server and gives the browser only a random id, while a token carries the login state inside itself and is checked by its signature.
- A signed token cannot be revoked by deleting something, so logout and a stolen token stay valid until the token expires unless you add a server-side deny list.
- A token kept in localStorage is readable by any script on the page, so one XSS bug exposes it, while an HttpOnly cookie cannot be read by script.
- A cookie is attached by the browser automatically, which is the reason cookie auth needs CSRF protection and bearer-header auth does not.
- For a first-party SPA with its own API, an HttpOnly session cookie is the simpler and safer default, and tokens earn their place with third-party clients or several backends.
Two ways to remember someone
HTTP forgets you between requests, so after login the server needs some way to recognise you again. There are two broad answers.
Session. The server keeps a record: “id x7Qe… belongs to user 1 until Friday.” The browser only holds the random id. Every request, the server looks the id up.
Token. The server hands over a signed statement: “user 1, valid until 3:15 pm,” with a signature only the server can produce. The browser holds the whole statement, and every request carries it. The server checks the signature and reads the contents. It looks nothing up.
The coat-check analogy from the last lesson fits the session. A token is more like a concert wristband: the guard checks that the band is genuine and not expired, and does not phone the box office.
The shape most people mean by “token” is a JWT: three base64 parts (header, payload, signature) joined by dots. The payload is readable by anyone, only unforgeable. Never put secrets in it. The broader comparison of schemes sits in JWT, API keys and session auth.
What each one costs
I built the token side with Hono’s JWT helper to see the behaviour rather than assume it (Hono 4.13.20):
const token = await sign({ sub: 1, exp: Math.floor(Date.now()/1000) + 900 }, secret, "HS256");
It produced a three-part string whose payload decoded to {"sub":1,"exp":1795378321}. Verification returned the same payload. Then I did what logout does with a token: nothing, because there is nothing server-side to delete. Verification still succeeded. Changing the last characters of the signature raised JwtTokenSignatureMismatched, so forgery is caught but revocation is not free.
That is the central trade-off:
| Session cookie | Signed token | |
|---|---|---|
| State lives | On the server | In the token |
| Lookup per request | Yes, a database or cache hit | No, a signature check |
| Logout | Delete the row, instant | Valid until expiry, unless you keep a deny list |
| Stolen credential | Revoke it | Wait for expiry or revoke by list |
| Scales across services | Needs shared store | Any service with the key can verify |
The “no lookup” advantage matters when many separate services must verify identity. For one API and one database, a session lookup is a primary-key read, and the “stateless” benefit is mostly theoretical. Meanwhile you lose the ability to say “sign this person out everywhere, now.” Most token systems paper over that with short-lived access tokens plus a refresh token stored server-side, which is a session by another name.
Where the credential lives in the browser
This is the question a SPA adds. A token has to be stored somewhere your JavaScript can send it:
- In
localStorage. Any script on the page can read it. One XSS bug, or one compromised npm dependency, and the attacker copies the token and uses it from anywhere. - In an
HttpOnlycookie. Script cannot read it at all. An XSS attacker can still make requests from the victim’s browser while the page is open, but cannot take the credential away with them.
Neither makes XSS harmless. HttpOnly changes the damage from “attacker has your credential indefinitely” to “attacker can act only while the tab is open”. Many real teams put the access token in an HttpOnly cookie for exactly this reason, which erases the main advantage of “just send it in a header”. Browser storage, cookies and sessions and authentication patterns for frontend apps cover the browser’s side.
The CSRF counterweight
Cookies have a cost tokens in headers do not. The browser attaches a cookie to a request no matter which site caused it. A malicious page can make your browser send POST /api/logout with your cookie. A token in an Authorization header is attached only by your own code, so another site cannot ride on it.
So cookie auth needs CSRF defences, and I ran the one Taskboard uses. A form-style POST with Origin: http://evil.example and a valid session cookie returned 403 Forbidden from Hono’s csrf middleware. That plus SameSite=Lax is the standard pair, covered fully in CSRF, XSS and cookie settings across layers.
Which one for Taskboard
Taskboard is a first-party SPA talking to its own API. The decision:
- Use an
HttpOnly,SameSite=Laxsession cookie. Instant logout, nothing readable by script, one lookup per request, and the CSRF defence is a few lines. - Add tokens only when a reason appears. A mobile app or third-party integrations authenticate with bearer tokens (often API keys or OAuth access tokens). Several backends verifying the same identity are another. These can run beside the session cookie; the API accepts either.
If you ever do reach for JWTs, keep the lifetime short, keep the signing key out of the repo, pin the algorithm on verify, and decide in advance how a user gets signed out. The cookie mechanics from the backend roadmap are in sessions and cookies in practice.
What the video covers
ByteByteGo’s “Session Vs JWT: The Differences You May Not Know!” is about seven minutes, published July 2024. Its description is only the channel’s boilerplate and carries no chapters, and I could not read a transcript, so I cannot list its points. The title and the channel’s usual animated format suggest a conceptual comparison, not a code walkthrough. The SPA-specific advice on storage, CSRF and Taskboard’s choice is this lesson’s own. Fireship’s session-versus-token video is linked as a faster second pass.
Where this fits
Cookies and tokens answer “who is this” for accounts you created yourself. Many users would rather click “Sign in with Google” than invent another password, which swaps the proof of identity but keeps your session. Next: social login with OAuth.
Check yourself
What can a server do to end a session that it cannot easily do to a JWT?
It can delete the session row, which makes the id useless immediately, whereas a JWT stays valid until it expires unless the server also keeps a deny list.
What did the verification of a token still return after I 'logged out' in my run?
It returned the same payload, because logout had nothing server-side to delete and the signature and expiry were still valid.
Why is a token in localStorage riskier than an HttpOnly cookie?
Any JavaScript on the page can read localStorage, so a single XSS bug can copy the token, while script cannot read an HttpOnly cookie.
Which approach needs CSRF protection, and why?
Cookie auth does, because the browser attaches the cookie to requests that another site triggers, whereas a token sent in an Authorization header is only attached by your own code.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.