Skip to content

13. Web Security for Frontend Engineers

“The browser is the only place where you routinely run code from strangers next to your bank account. Security is the art of keeping them in separate rooms.”

In the late summer of 2018, British Airways customers booking flights on the airline’s website and app entered their card details as usual. For about two weeks, every one of those card numbers — hundreds of thousands of them — was also quietly sent to a server controlled by criminals.

The attackers hadn’t breached a database. They had modified a JavaScript file the BA website already loaded — a common third-party library, hosted on BA’s own servers — appending around twenty-two lines of code. Those lines listened for the payment form’s submit button and, when clicked, serialized the form’s fields and posted them to a domain chosen to look plausible. The page looked and worked exactly as before. Nothing on the server side changed. The theft happened entirely in the customers’ browsers.

The group behind it was one of several known as Magecart, specializing in exactly this: skimming payment forms with injected JavaScript. The UK’s data-protection regulator eventually fined BA around £20 million.

The lesson for a frontend engineer is uncomfortable: any JavaScript running on your page has the same power as your JavaScript. It can read every field, every cookie not marked HttpOnly, every piece of DOM, and send it anywhere. Web security on the frontend is mostly about controlling which code runs on your page, and what it’s allowed to talk to.

The browser’s core security rule is the same-origin policy (SOP). An origin is scheme + host + port (https://lumen.example.in:443). The rule, roughly:

A page can embed resources from anywhere, but can only read data from its own origin.

So lumen.example.in can include an image, script, stylesheet or iframe from cdn.other.com. But its JavaScript can’t read the pixels of that cross-origin image from a canvas, can’t read the DOM of a cross-origin iframe, and can’t read the response body of a cross-origin fetch — unless the other origin explicitly allows it.

Without SOP, any site you visit could fetch('https://mail.google.com/') with your cookies attached and read your inbox. SOP is why it can’t.

Same-origin policyA page on lumen.example.in. Green arrows show it can embed scripts, images and iframes from other origins. A red blocked arrow shows it cannot read a cross-origin fetch response or the DOM of a cross-origin iframe. A dashed arrow labelled CORS shows the other origin can grant read access with Access-Control-Allow-Origin.lumen.example.inyour page + its JScdn.other.com (script, img)api.other.com (fetch)bank.com (iframe DOM)embed ✓read response ✗ (unless CORS)read DOM ✗
Figure 13.1. The same-origin policy: embedding across origins is allowed; reading across origins is not, unless the other origin opts in (CORS).

Cross-Origin Resource Sharing is the way a server relaxes the same-origin policy for its own responses. It’s a server opt-in, enforced by the browser.

A request is “simple” if it’s a GET, HEAD or POST with only basic headers and a basic content type (text/plain, application/x-www-form-urlencoded, multipart/form-data). The browser sends it, with an Origin: https://lumen.example.in header. The server responds; if the response includes Access-Control-Allow-Origin: https://lumen.example.in (or *), the browser lets your JS read it. If not, the request still happened — the server still processed it — but your JS gets a CORS error and can’t see the response.

That’s important: CORS protects reading, not sending. Simple cross-origin requests were always possible (a plain HTML form can POST anywhere), so CORS didn’t forbid them.

Anything else — PUT, DELETE, PATCH, Content-Type: application/json, custom headers like Authorization — first triggers a preflight: the browser sends an OPTIONS request asking “would you accept a PUT from this origin with these headers?” The server answers with Access-Control-Allow-Methods, Access-Control-Allow-Headers, and optionally Access-Control-Max-Age to cache the answer. Only if the preflight succeeds does the browser send the real request.

Preflights cost a round trip (Chapter 5). On Priya’s network, an API call with a JSON body to a different origin costs an extra ~80 ms unless the preflight is cached. One fix is architectural: put your API on the same origin (e.g., /api proxied by your server or CDN).

CORS preflightBrowser and API server timelines. First, an OPTIONS preflight with Origin and Access-Control-Request-Method PUT and Request-Headers content-type. The server responds 204 with Allow-Origin, Allow-Methods, Allow-Headers and Max-Age. Then the real PUT request with JSON body, and the response with Allow-Origin, which the browser lets JavaScript read.Browserapi.other.comOPTIONS · Origin · Request-Method: PUT204 · Allow-Origin · Allow-Methods · Max-AgePUT /essays/1 · application/json200 · Access-Control-Allow-Origin → JS can read
Figure 13.2. A preflighted CORS request. The OPTIONS round trip happens before the real request; Access-Control-Max-Age lets the browser skip it for a while.

Credentials, and why “just add *” fails

Section titled “Credentials, and why “just add *” fails”

By default, cross-origin fetch doesn’t send cookies. With credentials: 'include', it does — and then the rules tighten: the server must respond with Access-Control-Allow-Credentials: true and an explicit origin in Access-Control-Allow-Origin. The wildcard * is not allowed with credentials. That’s deliberate: “any website may read responses made with this user’s cookies” is precisely the attack SOP exists to stop.

Which leads to the most dangerous CORS bug: a server that reflects whatever Origin it receives into Access-Control-Allow-Origin and sets Allow-Credentials: true. That’s equivalent to turning SOP off for your API. Use an explicit allow-list of origins, and add Vary: Origin so caches don’t serve one origin’s CORS headers to another.

XSS: when your page runs someone else’s code

Section titled “XSS: when your page runs someone else’s code”

Cross-site scripting is injecting script into a page so it runs with the page’s origin — its cookies (unless HttpOnly), its DOM, its APIs. Three flavours:

  • Stored XSS — malicious content saved in your database (a comment containing <img src=x onerror="steal()">) and rendered to every viewer.
  • Reflected XSS — malicious content in a URL parameter echoed into the page (/search?q=<script>…), delivered by tricking someone into clicking a link.
  • DOM-based XSS — entirely client-side: your JS reads attacker-controlled input (location.hash, postMessage data) and writes it into a dangerous sink (innerHTML, document.write, eval, setTimeout with a string, element.setAttribute('href', …)).

Why React mostly protects you, and where it doesn’t

Section titled “Why React mostly protects you, and where it doesn’t”

React escapes values interpolated as text: <p>{comment}</p> renders <script> as visible characters, not as a tag. That eliminates most XSS by default. The holes:

  • dangerouslySetInnerHTML — the name is honest. If the HTML came from users (or from a CMS editors can write to, or from markdown rendered without sanitizing), sanitize it with a well-maintained sanitizer (like DOMPurify) first.
  • URLs: <a href={user.website}> — if website is javascript:alert(document.cookie), clicking runs it. Validate URLs against an allow-list of schemes (https:, mailto:).
  • Refs and direct DOM: ref.current.innerHTML = x bypasses React entirely.
  • Server-rendered JSON in a script tag: serializing state into <script>window.__DATA__ = ${JSON.stringify(data)}</script> without escaping </script> lets data break out of the script tag.
  • Third-party scripts and tags: they run with full privileges. Remember BA.
XSS sources and sinksLeft: sources such as URL parameters, location hash, stored comments, CMS content, postMessage data. Right: dangerous sinks such as innerHTML and dangerouslySetInnerHTML, href with javascript: URLs, eval and string setTimeout, document.write, and inline JSON in script tags. Between them a sanitizer and CSP/Trusted Types box acts as a filter.Sources?q=… URL paramslocation.hashstored commentsCMS / markdownpostMessage datasanitize · validateCSP · Trusted TypesSinksinnerHTMLdangerouslySetInnerHTMLhref=“javascript:…”eval / setTimeout(str)inline JSON in <script>
Figure 13.3. Where XSS gets in. Sources are anything an attacker can influence; sinks are APIs that turn strings into code or markup. React escapes text, but not these sinks.

CSP is an HTTP response header that tells the browser what the page is allowed to load and execute. It’s defence in depth: if an attacker does inject markup, CSP can stop it from running.

A strong modern policy uses nonces and strict-dynamic:

Content-Security-Policy:
script-src 'nonce-R4nd0m' 'strict-dynamic';
object-src 'none'; base-uri 'none'; frame-ancestors 'self'
  • Only <script> tags carrying the per-response random nonce (<script nonce="R4nd0m">) run. Injected scripts don’t know the nonce.
  • strict-dynamic lets those trusted scripts load further scripts, so you don’t have to allow-list every CDN domain.
  • Inline event handlers (onclick="…") and javascript: URLs are blocked.
  • Roll out with Content-Security-Policy-Report-Only first, collect violation reports, fix, then enforce.

Domain allow-list policies (script-src https://cdn.example.com) are weaker than they look: if any allowed domain hosts user content or an old JSONP endpoint, attackers can use it. And remember polyfill.io (Chapter 2): an allow-listed domain that changes owner becomes the attacker.

Trusted Types attack DOM XSS at the source. With the CSP directive require-trusted-types-for 'script', dangerous sinks like innerHTML reject plain strings; they only accept TrustedHTML objects created by a policy you define (which sanitizes). Every injection point in your codebase now has to go through a small number of reviewed policies. Supported in Chromium for years and reaching other engines more recently; it’s one of the most effective defences for large apps.

Cross-site request forgery tricks a logged-in user’s browser into making a state-changing request to your site, with their cookies attached. A malicious page contains:

<form action="https://bank.example/transfer" method="POST">
<input name="to" value="attacker"><input name="amount" value="50000">
</form>
<script>document.forms[0].submit()</script>

If the bank relies only on the session cookie, the transfer happens. The classic defence is a CSRF token: a random value the server embeds in its own forms and checks on submission; the attacker’s page can’t read it (SOP).

SameSite=Lax as the default (Chapter 12) changed the landscape: cross-site POSTs no longer carry cookies, which kills the attack above. But don’t retire CSRF defences entirely: Lax still allows top-level GET navigations (so never change state on GET), older browsers and SameSite=None cookies exist, and same-site attacks from a compromised subdomain are still possible. Modern frameworks’ built-in protections (tokens, checking the Origin header on mutations) cost little; keep them.

Clickjacking loads your site in an invisible iframe on the attacker’s page, positioned so that the victim, thinking they’re clicking “Play video,” actually clicks “Delete account” on your site. The defence is to forbid being framed: Content-Security-Policy: frame-ancestors 'self' (or 'none'), with the older X-Frame-Options: DENY for legacy browsers.

If you load a script from a CDN, SRI lets you pin its exact contents:

<script src="https://cdn.example.com/lib@4.2.0/lib.min.js"
integrity="sha384-…base64hash…" crossorigin="anonymous"></script>

If the file’s hash doesn’t match, the browser refuses to run it. This would have blocked a modified file like BA’s (had it been on a CDN with SRI) and a swapped polyfill.io script — if the content was static. SRI doesn’t work for scripts designed to change (like polyfill.io’s user-agent-dependent responses, or tag managers), which is itself a signal: a third-party script that can’t be pinned is a script you’re trusting completely. The safest option is often to self-host.

HTTPS everywhere is table stakes (Chapter 5). HSTS (Strict-Transport-Security: max-age=31536000; includeSubDomains; preload) tells browsers to only ever use HTTPS for your domain, closing the window where a first http:// request could be intercepted and downgraded. Adding your domain to the browsers’ HSTS preload list extends that protection to the very first visit. Be sure before you preload: removing yourself is slow, and every subdomain must support HTTPS.

Repeat after Chapter 4: anything in a client bundle is public. API keys with write access, admin tokens, private endpoints, internal URLs, and feature flags revealing unreleased plans are all readable by anyone with DevTools. Scanning tools find leaked keys in public bundles within minutes.

Rules: secrets live on servers; the client calls your server, which calls the third party with the secret; keys that must be public (maps, analytics, publishable payment keys) are restricted by domain, scope and quota at the provider; CI scans for secrets in commits and build outputs.

Layers of frontend defenceConcentric layers from outside in: HTTPS and HSTS; CSP with nonces and frame-ancestors; Trusted Types and sanitization; framework escaping; HttpOnly SameSite cookies; and in the centre, minimal and pinned third-party code.HTTPS + HSTSCSP: nonces, strict-dynamic, frame-ancestorsTrusted Types + sanitizer for HTML sinksFramework escaping · HttpOnly + SameSite cookiesfewest possible third-party scripts, self-hosted or SRI-pinned
Figure 13.4. Defence in depth for the frontend. No single layer is enough; together they make an injection hard to achieve and hard to exploit.

British Airways (2018). A modified first-party JS file skimmed payment data for roughly two weeks before discovery; around 400,000 customers affected; a fine around £20 million. Defences that would have helped: monitoring of script integrity (detecting changes to production JS), CSP restricting where the page could send data (connect-src), and isolating the payment form in a payment provider’s iframe so the main page’s scripts couldn’t read card fields at all.

polyfill.io (2024), revisited. A trusted script URL embedded on a huge number of sites changed hands and started serving malicious code. Every site that had a <script src="https://cdn.polyfill.io/…"> was running the new owner’s JavaScript. CDNs and security vendors stepped in to rewrite or block the domain, and the domain’s registrar eventually took it down. Defences: self-host what you depend on; SRI where content is static; CSP restricting script sources; and periodically auditing every third-party origin your pages load.

You can explain the same-origin policy and why it exists; walk through simple and preflighted CORS and why * fails with credentials; classify XSS and list where React doesn’t protect you; write a nonce-based CSP and explain Trusted Types; explain CSRF and what SameSite did and didn’t fix; defend against clickjacking; use SRI and know its limits; set HSTS; and keep secrets out of bundles — with two real breaches to anchor it.

1. Does CORS stop a cross-origin request from reaching the server?

Not for simple requests — it stops the page from reading the response. Preflighted requests aren’t sent if the preflight fails.

2. Why is Access-Control-Allow-Origin: * rejected with credentials?

Letting any origin read responses made with the user’s cookies would defeat the same-origin policy.

3. Name two XSS holes React doesn’t cover.

dangerouslySetInnerHTML with untrusted HTML; javascript: URLs in href; direct DOM writes via refs; unescaped inline JSON.

4. What does strict-dynamic do in CSP?

Scripts trusted via nonce/hash may load further scripts, without allow-listing domains.

5. Why keep CSRF tokens if SameSite=Lax is the default?

Lax still allows top-level GETs, some cookies are SameSite=None, older clients exist, and same-site attackers (subdomains) aren’t covered.

Warm-up 1. Read the error. The console says a request was blocked by CORS policy, but the Network panel shows status 500. What’s going on?

Solution

The server errored and its error response lacked CORS headers, so the browser hid it. Fix the 500 (and add CORS headers to error responses too).

Warm-up 2. Spot the XSS. <a href={profile.url}>Website</a> in a React app. Safe?

Solution

No — javascript: URLs execute on click. Validate the scheme.

Warm-up 3. Preflight or not? fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body }) to another origin.

Solution

Preflighted — JSON content type isn’t a simple type.

Lab 4. CSP for Lumen. Add a nonce-based CSP in report-only mode to Lumen. Collect violations for a day of browsing, fix them, then enforce.

Hint

Generate a nonce per request on the server (or in middleware), add it to the header and to your script tags. Static exports need hashes instead of nonces.

Lab 5. Comment sanitizer. Add comments to Lumen that support basic formatting. Render through a sanitizer and verify <img src=x onerror=alert(1)> is neutralized.

Expected outcome

The image tag’s event handler is stripped; formatting tags remain.

Lab 6. Third-party inventory. List every origin Lumen loads scripts from. Self-host or SRI-pin each.

Expected outcome

Ideally zero third-party script origins on critical pages.

Lab 7. Security headers. Add HSTS, frame-ancestors, X-Content-Type-Options: nosniff and a sensible Referrer-Policy to Lumen. Verify with DevTools.

Hint

Set them at nginx or in the CDN’s headers configuration so every response carries them.

Staff 8. Third-party governance. Marketing wants to add a chat widget and two analytics tags. Write a policy for approving third-party scripts.

Model points

Owner and purpose; data accessed and privacy review; performance budget; loading strategy (after interaction, async); CSP impact; SRI/self-hosting where possible; exit plan; quarterly review.

Staff 9. Payment page design. Design how a checkout page should be built so that a compromised analytics script cannot read card numbers.

Model answer

Card fields hosted in the payment provider’s cross-origin iframes (SOP isolates them); minimal scripts on checkout; strict CSP with connect-src allow-list; script change monitoring.