CSRF, XSS and cookie settings across layers
Set HttpOnly, Secure and SameSite on the session cookie, stop cross-site requests with an Origin check, and keep script out of the page, layer by layer.
Sessions vs tokens in a SPACORS and cross-origin setupsAuthorization in the API and the UI
CSRF, XSS and cookie settings across layers
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- CSRF abuses the fact that the browser attaches your cookie to a request no matter which site triggered it, so the defence is to refuse requests that did not come from your own origin.
- XSS means an attacker's script runs inside your page, and from there it can act as the user, so the defence is to never turn untrusted text into markup or script.
- HttpOnly keeps script from reading the cookie, Secure keeps it off plain HTTP, and SameSite limits when the browser sends it with cross-site requests.
- SameSite=Lax blocks the cookie on cross-site POSTs but sends it on top-level link navigations, which is why it works as a default for a normal web app.
- Defences stack, so use SameSite, an Origin check for every state-changing request, and a correct CORS policy together, because each one covers a gap in the others.
Two attacks, one cookie
Taskboard’s session lives in a cookie. That cookie is a master key, so two different attacks aim at it from opposite directions.
CSRF (cross-site request forgery) works from outside your page. You are signed in to Taskboard. You visit evil.example, which contains a hidden form that submits POST https://taskboard.example/api/logout, or …/projects/1/delete. Your browser sends the request with your cookie attached, because that is what cookies do: they ride along with every request to their site, whoever caused it. The attacker never reads your cookie. They just borrow it.
XSS (cross-site scripting) works from inside your page. An attacker gets their script to run on your origin, perhaps through a comment that Taskboard renders as raw HTML. That script has your user’s full power: it can call your API, read what is on screen, and change it.
The defences differ, so keep them apart. This lesson goes layer by layer. The web security fundamentals for frontend lesson covers the same threats from the browser’s view.
Cookie attributes
Three attributes on the session cookie do most of the work. From the earlier login, Taskboard sends:
set-cookie: sid=…; Max-Age=604800; Path=/; HttpOnly; SameSite=Lax
HttpOnly: JavaScript cannot read the cookie throughdocument.cookie. An XSS bug can no longer copy it. It does not stop the attacker’s script from making requests, since the browser still attaches the cookie.Secure: the browser sends the cookie only over HTTPS, so it cannot be sniffed on a café network. Taskboard’s local build leaves it off, because it runs on plain HTTP; production must turn it on, which is easy to forget because nothing breaks locally.SameSite: governs whether the cookie is sent when the request comes from another site.Strict: never on cross-site requests, including a click on a link from an email. Safest, and annoying: users arrive signed out.Lax: not sent on cross-site POSTs, iframes or fetches, but sent on top-level navigations with a safe method like GET. This is the sensible default.None: always sent, and requiresSecure. Needed only for genuine cross-site embedding.
The video below covers these three modes. Chromium-based browsers treat a cookie without the attribute as Lax, but not every browser does, so set it explicitly and do not depend on a default. Browser storage, cookies and sessions has the full attribute list.
One trap links back to CORS and cross-origin setups: “same site” ignores the port. localhost:5173 and localhost:8787 are the same site, so Lax cookies flow between them in development. In production, if the client is app.example.com and the API is api.other.io, the browser sees a cross-site request and Lax stops sending the cookie. Put both under one registrable domain, or serve them from one origin.
The server’s CSRF check
SameSite is a good first layer, not the only one: older browsers, subdomain takeovers and misconfiguration can all weaken it. The second layer is the server refusing requests whose Origin header is not yours. Hono ships a middleware:
.use("/api/*", csrf({ origin: ["http://localhost:5173"] }))
I tested it with the session cookie attached, claiming the request came from an untrusted origin:
- A form-encoded POST with
Origin: http://evil.examplereturned403 Forbidden. - A
text/plainPOST, the other content type a hidden form can send, also returned403. - A JSON POST with the same origin returned
201: the project was created.
That last result needs honest explanation. Hono’s middleware only checks the content types an HTML form can produce, which are the dangerous “simple” ones. A JSON body from another origin cannot be sent by a plain form, and a browser would first send a preflight asking the API whether evil.example may do this. My CORS configuration answers “no”, so the browser would block the real request. But curl performs no preflight, which is why it went through. The protection for JSON therefore depends on the CORS policy being correct. That is fine, and it is a good reason to keep the allow-list tight, and to add a cheap belt-and-braces rule: for every state-changing method, if an Origin header is present and not on the list, reject it, whatever the content type.
A second small finding: the middleware’s refusal was the plain text Forbidden, not the JSON error shape from the error handling lesson. A client that parses every failure as JSON would choke on it. Worth fixing with a custom failure response.
Classic CSRF tokens (a secret in each form that the attacker cannot guess) are the older answer, and remain useful when you must support browsers or flows where SameSite and Origin are unreliable. For a modern SPA with a JSON API, SameSite=Lax plus an Origin check plus strict CORS covers it.
Keeping script out of the page
XSS defence lives in the UI layer and in what the API stores.
- Never turn user text into markup. React escapes text in JSX by default, so
{comment.body}is safe. The danger isdangerouslySetInnerHTML,innerHTML, and building HTML strings. If Taskboard comments support formatting, sanitize with a maintained library on a strict allow-list, and prefer a restricted markup such as Markdown rendered by a safe renderer. - Validate and encode on the way out. The API stores whatever it is given; the output context decides the encoding. Do not rely on “I stripped
<script>on input.” - Send a Content Security Policy. A CSP header tells the browser which scripts may run, so an injected inline script fails even if the injection succeeded. Security headers and CSP shows the header in one framework; the header is the same everywhere.
- Mind third-party scripts. A tag manager or analytics script runs with the same power as yours. Securing Node dependencies and supply chain is the server-side counterpart for npm.
HttpOnly turns an XSS bug from “attacker takes the session” into “attacker acts during the visit”. That is a much smaller problem, though still a serious one.
A short stack checklist
| Layer | Do |
|---|---|
| Cookie | HttpOnly, Secure in production, SameSite=Lax, short Max-Age |
| API | Origin check on every state-changing method, tight CORS allow-list, JSON errors for refusals |
| Client | No raw HTML from users, no tokens in localStorage |
| Headers | CSP, and X-Content-Type-Options: nosniff |
| Deploy | Same site for client and API, HTTPS everywhere |
What the video covers
Cloud Explainers’ “Stop Session Hijacking: Secure, HttpOnly, and SameSite Flags Explained” is about eight and a half minutes, published June 2026. Its description says it covers the Secure flag for HTTPS-only transmission, the HttpOnly flag against script-based cookie theft through XSS, and the SameSite attribute (Strict, Lax and None) against CSRF. It also lists two extras: disabling the HTTP TRACE method and the __Secure- and __Host- cookie name prefixes. It is about cookie attributes, so the Origin check, CORS and output-escaping parts of this lesson are my own. I could not read a transcript, so I rely on the title and description. Web Dev Simplified’s CSRF video is linked for the token-based defence, and Hussein Nasser’s 2020 walk-through of SameSite by example for a hands-on look at the three modes.
Where this fits
That finishes auth: accounts, sessions, OAuth, permissions and cookie hardening. With people signed in, the interesting part begins: an app that reacts to them. Next: server state vs UI state.
Check yourself
What does HttpOnly stop, and what does it not stop?
It stops page script from reading the cookie, so an XSS bug cannot copy it, but the attacker's script can still send requests from the victim's open tab.
Why does SameSite=Lax still allow clicking a link to Taskboard from an email?
Lax sends the cookie on top-level navigations that use a safe method such as GET, so the user stays signed in, while cross-site POSTs and embedded requests do not carry it.
In my run, which cross-origin request from an untrusted origin got through?
A JSON POST sent with curl succeeded, because the Hono CSRF middleware only checks form-style content types and curl never performs the preflight a browser would.
Why does a correct CORS policy still matter if CSRF protection exists?
For JSON requests the browser's preflight is what stops an untrusted origin, so the CORS allow-list is part of the CSRF defence and has to be right.
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.