Skip to content

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.

21 min read0/5 questions

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.example and https://api.shop.example are different origins but the same site. Cookies and SameSite work 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, a postMessage) 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:

SinkWhy it is dangerous
el.innerHTML, outerHTML, insertAdjacentHTML, document.writeParses 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 inputA javascript: URL runs code when followed
iframe.srcdocA 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's v-html, Svelte's {@html}, Angular's bypassSecurityTrustHtml.
  • 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 block javascript: URLs in href, but other frameworks and older code do not, and data: URLs or open redirects are still yours to handle.
  • Refs and effects that write innerHTML directly, 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:

JavaScript
// Escaping for an HTML text context: what React does for {value}function escapeHtml(text) { return String(text) .replaceAll("&", "&amp;") .replaceAll("<", "&lt;") .replaceAll(">", "&gt;") .replaceAll('"', "&quot;") .replaceAll("'", "&#39;");} console.log(escapeHtml(`<img src=x onerror="alert(1)">`)); // Escaping does NOT make a URL safe. Check the scheme instead.function safeHref(input) { try { const url = new URL(input, "https://shop.example"); return ["https:", "http:", "mailto:"].includes(url.protocol) ? url.href : "#"; } catch { return "#"; }} for (const link of [ "https://docs.example/guide", "/account/orders", "javascript:alert(document.cookie)", " JaVaScRiPt:alert(1)", "data:text/html,<script>alert(1)</script>",]) { console.log(JSON.stringify(link).padEnd(46), "->", safeHref(link));} // Open redirect check: only allow same-origin paths for ?next=function safeNext(next) { const url = new URL(next, "https://shop.example"); return url.origin === "https://shop.example" ? url.pathname + url.search : "/";}console.log(safeNext("/checkout?step=2"), safeNext("//evil.example/login"), safeNext("https://evil.example"));
Output
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.

Quick check
A React profile page renders <a href={user.website}>Website</a> and <p>{user.bio}</p>, both from user input. Where is the real risk?
Need a nudge? A hint rules out a wrong answer.

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 carrying nonce="R4nd0mPerRequest" run. The server generates a fresh random value for every response. An injected <script> cannot guess it, and inline handlers like onerror="..." 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 when strict-dynamic is present).
  • object-src 'none' and base-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 older X-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 it in order4 steps

Put a safe CSP rollout in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Layers of XSS defence
  1. Framework escapingtext and attributes are safe by default
  2. Safe URLs and sanitisingscheme allowlist, DOMPurify for real HTML
  3. Trusted Typessinks refuse plain strings
  4. Strict CSPinjected scripts do not run
  5. HttpOnly cookiesa script that runs cannot steal the session

Most XSS never happens because the framework treats data as text. Keep it that way: avoid the escape hatches.

1/4

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:

AttributeEffect
HttpOnlyJavaScript cannot read it via document.cookie
SecureOnly sent over HTTPS
SameSite=LaxNot sent on cross-site subrequests or POSTs; sent when the user follows a link to you
SameSite=StrictNever sent on any cross-site request, even following a link
SameSite=NoneAlways sent (requires Secure); only for genuine cross-site use like embedded widgets
__Host- name prefixBrowser 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 the pairs0/4 matched

Match each cookie setting to the attack it limits.

Choose an item, then its match on the other side.

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.

A classic CSRF attack
Victim's browserevil.examplebank.examplelog inopen a linkhidden auto-submitting formPOST /transfer + cookie200 transfer done

The victim signs in. The bank sets a session cookie.

1/5

Defences, from the default you get for free to the belt-and-braces:

  1. SameSite=Lax or Strict session cookies. The cross-site POST above arrives without the cookie, so it is just an anonymous request.
  2. Never change state on GET. Lax still sends cookies when the user follows a link, so GET /account/delete?confirm=1 is exploitable with a plain link.
  3. Check where the request came from. Browsers send an Origin header on POSTs and a Sec-Fetch-Site header (same-origin, same-site, cross-site, none) on modern requests. Reject state-changing requests that are not same-origin.
  4. 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.

Quick check
The session cookie is SameSite=Lax. Which endpoint is still exploitable by a link on another site?
Need a nudge? A hint rules out a wrong answer.

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 Origin header back as Access-Control-Allow-Origin together with Access-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.

JavaScript
// A naive deep merge, the kind found in many hand-written utilsfunction merge(target, source) { for (const key in source) { if (typeof source[key] === "object" && source[key] !== null) { if (typeof target[key] !== "object") target[key] = {}; merge(target[key], source[key]); } else { target[key] = source[key]; } } return target;} // The attacker controls this JSON, e.g. a "settings" request bodyconst body = JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}}');const settings = merge({}, body); const someOtherUser = {};console.log("settings.theme:", settings.theme);console.log("someOtherUser.isAdmin:", someOtherUser.isAdmin);console.log("({}).isAdmin:", ({}).isAdmin); // Clean up the damage for the next part of the demodelete Object.prototype.isAdmin; // Fixed: skip dangerous keys and only copy own propertiesconst BLOCKED = new Set(["__proto__", "constructor", "prototype"]);function safeMerge(target, source) { for (const key of Object.keys(source)) { if (BLOCKED.has(key)) continue; const value = source[key]; if (typeof value === "object" && value !== null) { if (!Object.hasOwn(target, key) || typeof target[key] !== "object") target[key] = {}; safeMerge(target[key], value); } else { target[key] = value; } } return target;} safeMerge({}, body);console.log("after safeMerge, ({}).isAdmin:", ({}).isAdmin);
Output
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.

Predict the outputJavaScript

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);
Need a nudge? Hints walk you through it.

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 .env files out of git (.env* in .gitignore), and commit an .env.example with 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.
Key terms
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, eval or a javascript: 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.