読み物Application Security

Level: Intermediate

Cross-Site Scripting (XSS), CSRF, and Browser Defenses

How XSS and CSRF work, why framework escaping helps but isn't the whole story, and how sanitization, Content Security Policy, SameSite cookies, and CSRF tokens fit together.

Edeeson Opina9 min read

An Intermediate lesson card: lesson 8 of the Security & Privacy series, Cross-Site Scripting, CSRF, and Browser Defenses, with the Miso fox walking.

What you’ll learn

  • Distinguish reflected, stored, and DOM-based XSS
  • Apply the right encoding for each output context
  • Deploy a nonce-based Content Security Policy
  • Prevent CSRF with SameSite cookies, tokens, and origin checks
On this page
  1. Before you start
  2. What XSS is and why it's serious
  3. A vulnerable example
  4. Output encoding depends on context
  5. When you must render HTML: sanitize
  6. Content Security Policy
  7. Trusted Types
  8. What CSRF is
  9. Defending against CSRF
  10. Verifying your defenses
  11. Common mistakes and troubleshooting
  12. Practical exercise: break and fix locally
  13. Key takeaways
  14. References
  15. What's next

Two of the classic web vulnerabilities live in the browser. Cross-site scripting (XSS) lets an attacker run their own JavaScript inside your page, with full access to what the user sees and can do. Cross-site request forgery (CSRF) lets another website make the user's browser send a request to yours, riding on their signed-in session. This lesson explains how each works, why modern frameworks prevent most but not all XSS, and how output encoding, sanitization, Content Security Policy, SameSite cookies, and CSRF tokens fit together.

Before you start

You should understand cookies, SameSite, and the same-origin policy from How HTTPS, TLS, Cookies, and Browser Security Work, and have read OWASP Top 10 Explained, where XSS is part of A05 Injection. Examples use TypeScript, React, and Express. Try them only in a local project.

What XSS is and why it's serious

XSS happens when untrusted data ends up in a page in a way the browser interprets as code. The injected script runs with your site's origin, so the same-origin policy doesn't protect you: it can read the page, call your APIs as the user, change what the user sees (a fake "session expired, sign in again" form, for example), and send data anywhere. HttpOnly stops it from reading the session cookie directly, but it can still act as the user while the page is open.

There are three common forms:

  • Reflected XSS: input from the request, such as a search term in the URL, is echoed into the response. The attacker sends the victim a crafted link.
  • Stored XSS: input is saved, such as a comment or a profile name, and shown to other users later. It affects everyone who views it.
  • DOM-based XSS: the vulnerability is entirely in client-side JavaScript that takes data from the URL, storage, or messages and writes it into the page unsafely.

A vulnerable example

insecure-search-page.tsTypeScript
// INSECURE TEACHING EXAMPLE: the query is inserted into HTML without encoding.
app.get("/search", (req, res) => {
  res.send(`<h1>Results for ${req.query.q}</h1>`);
});

A request with q set to <img src=x onerror=alert(document.domain)> makes the browser run the attacker's code. The same mistake on the client side looks like this:

insecure-dom.tsTypeScript
// INSECURE TEACHING EXAMPLE: DOM-based XSS from the URL fragment.
document.querySelector("#greeting")!.innerHTML = `Hello, ${decodeURIComponent(location.hash.slice(1))}`;

Output encoding depends on context

The core defense is to encode untrusted data for the exact place it goes, so the browser treats it as text, never as markup or code. The right encoding depends on the context:

  • HTML text (between tags): replace <, >, &, ", and ' with HTML entities. Frameworks such as React, Vue, Angular, and Svelte do this automatically for values in templates.
  • HTML attributes: always quote attribute values and encode them. Framework attribute bindings do this, but some attributes are dangerous whatever the encoding: event handlers (onclick), style, and srcdoc.
  • URLs in href or src: encoding isn't enough, because a javascript: URL is valid text. Parse the URL and allow only http: and https: (and mailto: if needed).
  • JavaScript and CSS contexts: don't put untrusted data inside <script> blocks or style rules. Pass data as JSON in a data- attribute or a <script type="application/json"> element, and read it with JSON.parse.

In practice, the safe approach in React is simply to render values as text:

greeting.tsxTSX
export function Greeting({ name }: { name: string }) {
  return <h1>Hello, {name}</h1>; // React encodes the value as text
}

export function SafeLink({ href, children }: { href: string; children: React.ReactNode }) {
  const url = URL.canParse(href) ? new URL(href) : null;
  const safe = url && (url.protocol === "https:" || url.protocol === "http:") ? url.toString() : "#";
  return <a href={safe} rel="noopener noreferrer">{children}</a>;
}

On the DOM side, use textContent instead of innerHTML whenever you're inserting text:

dom.tsTypeScript
document.querySelector("#greeting")!.textContent = `Hello, ${decodeURIComponent(location.hash.slice(1))}`;

When you must render HTML: sanitize

Sometimes you really do need to display user-provided HTML, such as rich text from an editor. Encoding would show the tags as text, so instead you sanitize: parse the HTML and remove everything not on an allowlist of safe elements and attributes. Don't write your own sanitizer with regular expressions; browsers parse HTML in surprising ways. Use a maintained library such as DOMPurify:

rich-text.tsxTSX
import DOMPurify from "dompurify";

export function RichText({ html }: { html: string }) {
  const clean = DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

Sanitize as close to rendering as possible, keep the library updated (sanitizer bypasses are found and fixed regularly), and consider a simpler format such as Markdown with raw HTML disabled when you don't need full HTML.

Content Security Policy

Content Security Policy (CSP) is a response header that tells the browser which scripts may run. It's a second line of defense: if an XSS bug slips through, a strict policy can stop the injected script from executing. The approach recommended by OWASP and the major browser vendors is a nonce-based strict policy:

HTTP
Content-Security-Policy: script-src 'nonce-R4nd0mPerResp0nse' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'self'
  • The server generates a new random nonce for every response and adds it to each legitimate <script nonce="..."> tag. Injected scripts don't know the nonce, so they're blocked.
  • 'strict-dynamic' lets scripts you trusted load further scripts, which makes the policy practical with bundlers and tag managers.
  • object-src 'none' and base-uri 'none' close two common bypasses.
  • Inline event handlers like onclick="..." are blocked, so move them into script files.
csp.tsTypeScript
import { randomBytes } from "node:crypto";

app.use((req, res, next) => {
  const nonce = randomBytes(16).toString("base64");
  res.locals.cspNonce = nonce; // templates add nonce="..." to each script tag
  res.setHeader(
    "Content-Security-Policy",
    `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'self'`,
  );
  next();
});

Roll it out with Content-Security-Policy-Report-Only first, which reports violations without blocking, then switch to enforcement. Frameworks such as Next.js document how to generate nonces in middleware.

Trusted Types

For DOM-based XSS, the CSP directive require-trusted-types-for 'script' makes the browser refuse plain strings in dangerous sinks such as innerHTML, forcing code to go through a reviewed policy. Browser support has been expanding; check MDN's compatibility table before relying on it.

What CSRF is

CSRF exploits the fact that browsers attach cookies to requests automatically. Suppose a user is signed in to your app, and visits a malicious page that contains:

HTML
<!-- INSECURE TEACHING EXAMPLE: a page on another site submitting a form to yours -->
<form action="https://your-app.test/account/email" method="POST">
  <input type="hidden" name="email" value="attacker@evil.test" />
</form>
<script>document.forms[0].submit();</script>

If your app relies only on the session cookie and the browser sends it, the email change goes through. The attacker can't read the response (same-origin policy), but they don't need to: the damage is the state change.

Defending against CSRF

Use layers, starting with the cheapest:

  1. SameSite cookies. A session cookie with SameSite=Lax isn't sent on cross-site POST requests, which stops the classic attack in modern browsers. Strict is stronger. This is a strong baseline, but don't make it your only defense: it doesn't protect against requests from your own subdomains (which count as same-site), and older or misconfigured clients may behave differently.
  2. Never change state with GET. Lax cookies are sent on top-level GET navigations, so a GET that deletes something is still forgeable.
  3. Check the origin. Browsers send an Origin header on cross-origin POSTs, and modern browsers send Sec-Fetch-Site. Reject state-changing requests that come from another site.
  4. CSRF tokens. For traditional forms, include a random token tied to the session in a hidden field, and verify it on submit. An attacker's page can't read it.
csrf-origin.tsTypeScript
import type { NextFunction, Request, Response } from "express";

const ALLOWED_ORIGINS = new Set(["https://your-app.test"]);

export function rejectCrossSite(req: Request, res: Response, next: NextFunction) {
  if (["GET", "HEAD", "OPTIONS"].includes(req.method)) return next();
  const fetchSite = req.get("Sec-Fetch-Site");
  if (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none") return res.sendStatus(403);
  const origin = req.get("Origin");
  if (origin && !ALLOWED_ORIGINS.has(origin)) return res.sendStatus(403);
  next();
}

Many frameworks build these checks in. Next.js Server Actions, for example, only accept POST requests and compare the Origin header with the host. Know what your framework does, and don't disable it.

APIs that authenticate with an Authorization header instead of cookies aren't exposed to CSRF in the same way, because browsers don't add that header automatically. Keep it that way: don't also accept the session cookie on those routes.

Verifying your defenses

  • Write a test that sends <script>alert(1)</script> and "><img src=x onerror=alert(1)> through every input that's displayed, and asserts the response contains the encoded text, not the tags.
  • Check with developer tools that the CSP header is present and that the console shows no violations on normal pages.
  • From a different local origin (for example a second dev server on another port), try posting a form to your app and confirm it's refused.
xss.test.tsTypeScript
import request from "supertest";
import { expect, it } from "vitest";
import { app } from "./app";

it("encodes search terms in the results page", async () => {
  const payload = `<img src=x onerror=alert(1)>`;
  const res = await request(app).get("/search").query({ q: payload });
  expect(res.text).not.toContain(payload);
  expect(res.text).toContain("&lt;img src=x onerror=alert(1)&gt;");
});

Common mistakes and troubleshooting

  • dangerouslySetInnerHTML or innerHTML with unsanitized data. Search for both; each use should be justified and sanitized.
  • Unvalidated URLs in href. Encoding doesn't stop javascript: URLs; allow only safe schemes.
  • A CSP with 'unsafe-inline' in script-src. It undoes most of the protection. Use nonces.
  • Sanitizing on input, then editing the data later. Sanitize at output, where you know the context.
  • State changes over GET. Use POST, PUT, PATCH, or DELETE.
  • CORS confused with CSRF protection. CORS controls who can read responses; it doesn't stop a form post from being sent.

If a nonce-based CSP breaks a page, the browser console names the blocked script. It's usually an inline handler or a script tag missing the nonce.

Practical exercise: break and fix locally

In a local practice app:

  1. Build the insecure search page above and confirm a payload runs.
  2. Fix it with encoding (or a template engine that encodes) and add the test.
  3. Add a nonce-based CSP in report-only mode, fix every violation, then enforce it.
  4. Create a second local site on another port with the forged form, and confirm your SameSite cookie and origin check each stop it.

Key takeaways

  • XSS runs attacker code in your origin; encode untrusted data for its exact context, which frameworks do for text by default.
  • Validate URL schemes, sanitize HTML with a maintained library, and avoid raw HTML sinks.
  • A nonce-based strict CSP limits the damage of any XSS that slips through.
  • CSRF uses the browser's automatic cookies; defend with SameSite, no state changes on GET, origin checks, and tokens.

References

What's next

Both XSS and CSRF target the signed-in session. Secure Authentication, Authorization, and Session Management covers how sessions are created, protected, and ended, and how to check permissions on every request.

See every lesson in Security & Privacy: Building Secure Applications