Lesson 32 of 50JavaScript at work
Web Security for JavaScript Developers
Stop XSS, CSRF and token theft in real frontends: safe sinks, Content-Security-Policy, cookie flags, CORS limits, postMessage and prototype pollution.
A support ticket comes in: a customer says their account changed its delivery address on its own. Logs show the request came from the customer's own browser, with a valid session. The cause turns out to be a product review that contained a script, rendered by a "rich text" component someone added last quarter. Every visitor who opened that product page ran the attacker's code, inside your site, with their own login. Frontend security bugs look like this: no server was hacked, yet users were. This lesson covers the attacks that land on JavaScript developers' desks, how browsers defend against them, and the specific settings and habits that close each hole. The XSS section of the DOM lesson showed the basic innerHTML problem; here you go further.
The rules the browser enforces
Almost every web attack is about getting around one rule: the same-origin policy. An origin is scheme, host and port: https://shop.example:443. Code from one origin cannot read another origin's pages, storage or responses unless that origin allows it.
Two related ideas trip people up:
- A site is broader than an origin: the scheme plus the registrable domain.
https://app.shop.exampleandhttps://api.shop.exampleare different origins but the same site. Cookies andSameSitework at the site level, so a compromised subdomain is much closer to you than a stranger's domain. - The browser sends requests to other origins freely. Forms, images and scripts have always been able to hit any URL. What the same-origin policy blocks is reading the response. Keep that in mind for CSRF and CORS.
So an attacker has two broad options. Get their code to run inside your origin, which is XSS. Or make the victim's browser send a request to your origin from outside, carrying the victim's cookies, which is CSRF. Everything else is a variation.
XSS: the attacker's code in your origin
Cross-site scripting (XSS) is any way untrusted data ends up being run as code on your page. Once it runs, it is your code as far as the browser is concerned: it can read the page, call your APIs with the user's cookies, change their email address, and log keystrokes into your login form.
There are three kinds, named by where the payload lives:
- Stored XSS. The payload is saved on your server (a review, a profile bio, a file name) and served to every visitor. The most damaging kind, because one submission hits many users.
- Reflected XSS. The payload is in the request, usually the URL, and the server echoes it into the page. The attacker sends the victim a crafted link.
- DOM-based XSS. The payload never touches the server. Your own client-side JavaScript reads something attacker-controlled (
location.hash, a query parameter, apostMessage) and writes it into a dangerous place. Single-page apps make this kind more common.
Sources and sinks
Think of XSS as data flowing from a source the attacker controls to a sink that turns text into code. Sources include URL parts, form fields, API responses containing user content, postMessage data and even localStorage (if an earlier bug wrote to it). The sinks to recognise on sight:
| Sink | Why it is dangerous |
|---|---|
el.innerHTML, outerHTML, insertAdjacentHTML, document.write | Parses a string as HTML, including event handler attributes |
eval, new Function, setTimeout("string") | Runs a string as JavaScript |
a.href, location.href, iframe.src with user input | A javascript: URL runs code when followed |
iframe.srcdoc | A whole HTML document from a string |
jQuery $(html), .html() | innerHTML with extra steps |
What frameworks do, and where they stop
React, Vue, Angular and Svelte escape values you put in text and attributes. When you write <p>{review.body}</p>, React sets it as text, so <script> shows up as visible characters. This one default prevents most XSS, and it is why modern apps have far fewer holes than old server-rendered PHP.
Every framework also has an escape hatch, and the escape hatches are where the bugs are:
- React's
dangerouslySetInnerHTML, Vue'sv-html, Svelte's{@html}, Angular'sbypassSecurityTrustHtml. - URLs. Escaping makes text safe inside HTML, but
javascript:alert(1)contains nothing to escape.<a href={user.website}>is a classic hole. Recent React versions blockjavascript:URLs inhref, but other frameworks and older code do not, anddata:URLs or open redirects are still yours to handle. - Refs and effects that write
innerHTMLdirectly, bypassing the framework. - Markdown renderers and third-party widgets that output raw HTML.
- Server-rendered JSON put into a
<script>tag. A string containing</script>closes the tag early. Serialise with a function that escapes<.
Escaping must match the context: HTML text, an attribute, a URL and a JavaScript string all have different rules. Here is HTML escaping, which is what React does for you, and why it does nothing for a URL:
Press Run (⌘ Enter) to see what happens.Two lessons hide in that output. First, parse URLs with new URL() and check protocol against an allowlist; a blocklist checking for the string "javascript:" misses the version with spaces and mixed case. Second, //evil.example looks like a path but is a full URL to another site. Login pages with ?next= parameters are a favourite place for this open redirect bug, which makes phishing links look legitimate.
When you truly must render user HTML (a rich text editor, email previews, CMS content), sanitise it with a maintained library such as DOMPurify, which parses the HTML and removes scripts, event handlers and dangerous URLs while keeping formatting. Never write your own sanitiser with regexes; HTML parsing has too many quirks. Browsers are also adding a built-in Sanitizer API (element.setHTML()); check current support before relying on it.
<a href={user.website}>Website</a> and <p>{user.bio}</p>, both from user input. Where is the real risk?Content-Security-Policy and Trusted Types
Escaping and sanitising are about writing correct code. Content-Security-Policy (CSP) is a safety net for when someone does not: a response header telling the browser which scripts may run at all. A strict CSP looks like this:
Content-Security-Policy:
script-src 'nonce-R4nd0mPerRequest' 'strict-dynamic';
object-src 'none';
base-uri 'none';
frame-ancestors 'none''nonce-...': only<script>tags carryingnonce="R4nd0mPerRequest"run. The server generates a fresh random value for every response. An injected<script>cannot guess it, and inline handlers likeonerror="..."are blocked outright.'strict-dynamic': a script the nonce allowed may load further scripts, so bundlers and tag managers keep working without long domain allowlists (which are easy to bypass and are ignored whenstrict-dynamicis present).object-src 'none'andbase-uri 'none'close two old bypasses: plugins and a<base>tag that redirects relative script URLs.frame-ancestors 'none'stops other sites from embedding yours in an iframe, the defence against clickjacking, where an invisible frame of your site sits under a fake "Claim prize" button. It only works as a header, not in a<meta>tag, and replaces the olderX-Frame-Options.
Nonces need a server that renders each response, which frameworks like Next.js support. Fully static pages that are cached on a CDN cannot change a nonce per request, so they use hashes of the allowed inline scripts instead.
Avoid 'unsafe-inline' in script-src: it allows exactly the injected scripts CSP exists to block. And never switch a strict policy straight on in production. Roll it out in stages.
Put a safe CSP rollout in order.
- Tap the steps below in the right order.
Trusted Types go one step further. With require-trusted-types-for 'script' in your CSP, sinks like innerHTML throw if you pass them a plain string. They only accept a TrustedHTML object produced by a policy you define, so every path to a sink goes through one reviewed function:
const sanitize = trustedTypes.createPolicy("sanitize", {
createHTML: (dirty) => DOMPurify.sanitize(dirty),
});
preview.innerHTML = sanitize.createHTML(userHtml);Trusted Types turned DOM XSS from "search the codebase for every sink" into "review the policies". Chromium has supported them for years and the other engines have been adding them; check current support for your users' browsers.
Most XSS never happens because the framework treats data as text. Keep it that way: avoid the escape hatches.
Cookies, tokens and where to keep them
Login sessions usually ride on a cookie. Its attributes decide who can read it and when the browser sends it:
| Attribute | Effect |
|---|---|
HttpOnly | JavaScript cannot read it via document.cookie |
Secure | Only sent over HTTPS |
SameSite=Lax | Not sent on cross-site subrequests or POSTs; sent when the user follows a link to you |
SameSite=Strict | Never sent on any cross-site request, even following a link |
SameSite=None | Always sent (requires Secure); only for genuine cross-site use like embedded widgets |
__Host- name prefix | Browser enforces Secure, Path=/ and no Domain, so subdomains cannot set or override it |
A strong session cookie: Set-Cookie: __Host-session=...; HttpOnly; Secure; SameSite=Lax; Path=/. Chromium treats a cookie with no SameSite as Lax, but other browsers differ, so always set it explicitly.
Why not keep the token in localStorage? Because any script on the page can read localStorage: your code, every third-party script and any XSS payload. The token gets sent to the attacker's server and used from anywhere, for as long as it is valid. An HttpOnly cookie cannot be read by script at all.
Be precise about what that buys you, because interviewers probe it. HttpOnly does not make XSS harmless. Injected code can still call fetch("/api/address", { method: "POST", ... }) from your page, and the browser attaches the cookie. What HttpOnly prevents is theft: the attacker can only act while the victim has the page open, cannot reuse the session later, and leaves traces in your logs from the victim's browser. XSS prevention is still the real defence.
Match each cookie setting to the attack it limits.
CSRF: requests from somewhere else
Cross-site request forgery (CSRF) makes the victim's browser send a request to your site from another site, and relies on the browser attaching the victim's cookies.
The victim signs in. The bank sets a session cookie.
Defences, from the default you get for free to the belt-and-braces:
SameSite=LaxorStrictsession cookies. The cross-site POST above arrives without the cookie, so it is just an anonymous request.- Never change state on
GET.Laxstill sends cookies when the user follows a link, soGET /account/delete?confirm=1is exploitable with a plain link. - Check where the request came from. Browsers send an
Originheader on POSTs and aSec-Fetch-Siteheader (same-origin,same-site,cross-site,none) on modern requests. Reject state-changing requests that are not same-origin. - CSRF tokens for older stacks or when cookies must be
SameSite=None: a random value tied to the session that the page includes in each form or header, which another site cannot read.
Remember that SameSite works by site: a request from forum.shop.example to shop.example is same-site, so a takeover of any subdomain can bypass it. Origin checks are stricter.
SameSite=Lax. Which endpoint is still exploitable by a link on another site?CORS is not a firewall
CORS, covered in Working with APIs, decides whether a page on another origin may read your responses. It does not stop requests arriving: simple cross-site POSTs reach your server whatever your CORS headers say. It also does nothing against curl, scripts or servers, which ignore it entirely. So:
- CORS is never authentication. Every endpoint checks the session and permissions on the server.
- Do not reflect the request's
Originheader back asAccess-Control-Allow-Origintogether withAccess-Control-Allow-Credentials: true. That tells the browser any site may read your users' data with their cookies. Use an explicit allowlist.
postMessage, iframes and other edges
window.postMessage lets windows from different origins talk: a payment iframe, an embedded widget, an OAuth popup. Both ends have a classic bug:
// Sending: name the exact origin you expect, never "*"
paymentFrame.contentWindow?.postMessage({ type: "pay", amount }, "https://pay.example");
// Receiving: check origin before trusting anything
window.addEventListener("message", (event) => {
if (event.origin !== "https://pay.example") return;
if (event.data?.type !== "paid") return;
showReceipt(event.data.receiptId); // still treat data as untrusted input
});Any page can post to your window, so a listener without an origin check accepts commands from strangers. Use exact string comparison: origin.endsWith("pay.example") also matches evilpay.example.
Prototype pollution
JavaScript objects inherit from Object.prototype. If attacker-controlled keys reach a naive deep merge, a key named __proto__ walks up to that shared prototype and writes a property every object in the program now appears to have.
Press Run (⌘ Enter) to see what happens.On a server, that isAdmin check passing for everyone is a privilege escalation. In the browser, polluted properties have been chained into XSS through libraries that read options like innerHTML from objects. The fixes: validate input shapes with a schema library (Zod) before merging, block the three dangerous keys, use Map or Object.create(null) for dictionaries keyed by user input, and keep merge libraries patched.
What does this print?
const payload = JSON.parse('{"__proto__": {"role": "admin"}}');
const a = Object.assign({}, payload);
const b = { ...payload };
console.log(a.role, b.role, ({}).role);Secrets never ship to the browser
Everything in your bundle is public, including minified code and source maps. Build tools inline environment variables with a public prefix (NEXT_PUBLIC_, VITE_) into the JavaScript at build time, so a secret key behind one of those prefixes is published to every visitor. Secret keys stay on a server that your frontend calls.
Habits that prevent leaks:
- Keep
.envfiles out of git (.env*in.gitignore), and commit an.env.examplewith names but no values. - After a production build, search the output folder for key prefixes your providers use. It takes seconds and has caught real leaks.
- If a secret was ever committed or shipped, rotate it. Deleting it in a new commit does not remove it from git history or from copies people have already downloaded.
- Do not serve source maps publicly unless you are happy for people to read your original source; upload them to your error tracker instead.
- Load third-party scripts sparingly. Each one runs with full access to your origin. For files from a CDN,
integrity="sha384-..."(Subresource Integrity) makes the browser refuse a file that has been altered.
- same-origin policy
- The browser rule that code from one origin (scheme, host, port) cannot read another origin's data without permission.
- XSS
- Cross-site scripting: untrusted data executed as code inside your origin, stored, reflected or DOM-based.
- sink
- An API that turns a string into code or markup, such as
innerHTML,evalor ajavascript:URL. - Content-Security-Policy
- A response header listing which scripts may run; a strict policy uses per-response nonces and
strict-dynamic. - CSRF
- Cross-site request forgery: another site makes the victim's browser send a request that carries their cookies.
- SameSite
- A cookie attribute controlling whether the cookie is sent on requests started by other sites.
- prototype pollution
- Writing attacker-controlled properties onto
Object.prototype, so every object appears to have them.