Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 156 ยท Browser APIs

XSS, CSRF and Safe DOM Updates

Stop XSS by choosing safe DOM APIs, sanitizing HTML with an allowlist and adding CSP, and understand how CSRF works and how tokens and SameSite cookies stop it.

Two attacks account for a huge share of web-page security bugs, and they are easy to mix up. Cross-site scripting (XSS) tricks your page into running an attacker's code. Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a request to your server that the user never meant to make. They need different defenses, and a page can be safe from one and wide open to the other.

The JavaScript security basics lesson gave you the overview. This one goes deeper on the part you control every day: how you put data into the page, how to let users format text without letting them inject code, and how tokens and cookie settings shut down forged requests.

Everything in this lesson is defense in depth. No single technique is enough. Safe APIs stop most XSS, a sanitizer covers the cases where you truly need HTML, a Content Security Policy limits the damage of anything that slips through, and the server must still validate every request.

Where XSS comes from: sinks

Untrusted data (a comment, a name, a URL parameter, a field in an API response) becomes dangerous when it reaches a sink: an API that turns a string into live HTML or code. The common sinks are:

  • element.innerHTML, outerHTML and insertAdjacentHTML()
  • document.write()
  • eval(), new Function() and setTimeout("string", ...)
  • URL-valued properties such as a.href, when the value starts with javascript:
  • Inline event attributes like onclick="..." that you build from strings

Safe APIs do the opposite: they treat the string as plain text and never parse it as markup. The rule of thumb is simple: prefer textContent, setAttribute() for harmless attributes, and createElement(); keep innerHTML for strings you wrote yourself. See changing content and creating elements for the basics.

flowchart LR
  A["Untrusted data<br/>(user, URL, API)"] --> B{"How does it<br/>enter the page?"}
  B -->|"textContent / createElement"| C["Shown as text<br/>safe"]
  B -->|"innerHTML"| D["Parsed as HTML<br/>risky"]
  D --> E["Sanitize first<br/>or avoid"]

Choosing the sink decides whether the same string is text or code.

textContent versus innerHTML

Here is the same hostile comment written to the page three ways. The "attack" is harmless: it only logs a message and tints a box.

Three ways to show a hostile comment

The first box runs the injected handler (the box turns pink and the console reports it). The other two show the markup as visible characters. Notice that the attacker did not need a <script> tag: an <img> with a failing src and an onerror attribute is enough.

If you must build HTML from a template, escape every value first. This small helper replaces the five characters that matter:

JavaScript
function escapeHtml(value) {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

const html = `<li title="${escapeHtml(title)}">${escapeHtml(name)}</li>`;

Escaping works only for the context you wrote it for. It is fine for text and quoted attribute values, but not inside a <script> block, a style attribute or a URL. That is why textContent and DOM methods are better: they have no context to get wrong.

Dangerous URLs

A link built from user input has a second hole: the scheme. <a href="javascript:alert(1)"> runs code when clicked, and escapeHtml does nothing about it, because there are no special characters to escape. Allow only schemes you expect by parsing the value with the URL class:

JS Allowlist URL schemes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The URL parser normalizes tricks like mixed case and leading whitespace before you test the protocol. Testing the raw string with something like startsWith("javascript:") is how attackers get past filters.

Sanitizing: when users may use some HTML

Sometimes you really do want rich text: a comment editor with bold and links, or HTML from a CMS. Escaping would show the tags literally. Instead you sanitize: parse the HTML, keep only what you have approved, and throw away the rest. The key word is allowlist: list the tags and attributes that are OK and drop everything else. A blocklist ("remove <script>") always misses something.

The parser to use is DOMParser. It builds a document that is inert: scripts do not run and images are not loaded, so you can inspect the markup safely before using any of it.

A small allowlist sanitizer

Press the button: the bold text, the emphasis and the https link survive; the image, the script, the onclick and the javascript: link are gone, and the console shows the cleaned markup. Because the function builds new elements with createElement() and copies only values it chose, nothing from the attacker's markup can sneak through in an attribute you forgot about.

For production, do not maintain your own sanitizer. HTML parsing has many odd corners, and a battle-tested library (DOMPurify is the best known) is the safer choice. Newer browsers are also adding a built-in Sanitizer API with element.setHTML(string), which parses and cleans in one step. Check current browser support before relying on it, and fall back to a library where it is missing.

Sanitize where the HTML is used, and sanitize again if the rules change. Cleaning on the server when data is saved is not enough on its own: the stored text might be rendered by another app, or your allowlist might grow stricter later. Many teams store the original and sanitize on output.

Content Security Policy as a safety net

If a mistake lets markup through anyway, a Content Security Policy (CSP) limits what it can do. A strict policy forbids inline scripts and inline event handlers, so the onerror trick above simply does not run:

HTTP
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-RANDOM_PER_RESPONSE'; object-src 'none'; base-uri 'none'

Start with Content-Security-Policy-Report-Only so you can find what would break before you enforce anything. CSP is a safety net, not a replacement for safe DOM updates: you still fix the bug. The security lesson explains nonces and Trusted Types in more detail.

CSRF: forged requests that carry real cookies

Now the other attack. When a browser sends a request to a site, it automatically attaches that site's cookies, no matter which page triggered the request. Suppose you are logged in to bank.example and then visit evil.example. That page can contain a hidden form that posts to https://bank.example/transfer. Your browser dutifully adds your session cookie, the bank sees a logged-in user, and the money moves. The attacker never saw your cookie and never ran code on the bank's site. That is CSRF.

sequenceDiagram
  participant U as User's browser
  participant E as evil.example
  participant B as bank.example
  U->>E: Visit page
  E-->>U: Hidden form targeting bank.example/transfer
  U->>B: POST /transfer (session cookie attached automatically)
  B-->>U: Looks like a real request: transfer done

The cookie proves who the browser is, not that the user intended this action.

Defense 1: SameSite cookies

The SameSite attribute on the session cookie tells the browser when to include it on cross-site requests. SameSite=Lax (the default in modern browsers when the attribute is missing) withholds the cookie on cross-site POST requests, which kills the hidden-form attack. SameSite=Strict is stricter still, and withholds it even when the user simply clicks a link from another site. Set it from the server:

HTTP
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

JavaScript cannot set HttpOnly cookies at all (that is the point: scripts cannot read them, which limits what XSS can steal). See cookies for how browsers handle the other attributes.

Defense 2: anti-CSRF tokens

SameSite is a strong layer, but not a complete one (older browsers, sites that must use SameSite=None, and "same-site but not same-origin" subdomains all leave gaps). The classic defense is a CSRF token: a secret random value the server gives to your real page, which your JavaScript must send back with every state-changing request, in a header or in the body. A forged request from evil.example carries the cookie but cannot know the token, because the same-origin policy stops it from reading your page.

The demo below plays both roles in one script: a pretend server that issues and checks tokens, and a pretend attacker who has the cookie but not the token.

JS A pretend server that checks CSRF tokens

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In a real app, you pass the token with fetch() like this (read-only, since the sandbox here has no server):

JavaScript
const token = document.querySelector('meta[name="csrf-token"]').content;

await fetch("/transfer", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-CSRF-Token": token,
  },
  credentials: "same-origin",
  body: JSON.stringify({ to: "alice", amount: 20 }),
});

Notice the custom header. Browsers do not let a plain cross-site form add custom headers, and a cross-site fetch() with one triggers a CORS preflight that the server will refuse, so requiring a header is a second reason the forged request fails. Frameworks such as Laravel, Django and Rails generate and verify these tokens for you; your job on the front end is to make sure every POST, PUT, PATCH and DELETE carries it, and that state-changing actions never use GET.

XSS and CSRF are different problems

If an attacker achieves XSS on your page, they run code as your page, so they can read the CSRF token and make perfectly valid requests. CSRF tokens cannot save you from XSS. And a strict SameSite cookie does not stop script injection. That is why you need both sets of defenses.

A short checklist

  • Insert untrusted text with textContent or DOM methods, not innerHTML.
  • Allowlist URL schemes with the URL class before putting user links in href.
  • When users supply HTML, sanitize it with an allowlist (preferably a maintained library or the browser's Sanitizer API where available).
  • Ship a CSP, starting in report-only mode.
  • Mark session cookies HttpOnly; Secure; SameSite=Lax (or Strict).
  • Send a CSRF token with every state-changing request, and use GET only for reads.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about inserting a user's comment is the safest?

    textContent treats the string as plain text and never parses markup, so injected tags show up as visible characters.
  2. 2. Why is a blocklist sanitizer (removing script tags) weak?

    There are countless ways to run code besides script tags. An allowlist keeps only what you approved, so unknown tricks are removed by default.
  3. 3. What does a CSRF attack abuse?

    The attacker never runs code on your site; they make the victim's browser send a request that carries the victim's real cookies.
  4. 4. Why does a CSRF token stop a forged cross-site request?

    The same-origin policy stops evil.example from reading your page, so it cannot learn the secret token the server expects in the request.
  5. 5. If an attacker achieves XSS on your page, what happens to CSRF tokens?

    Injected code runs as your page, so it can read the token. This is why XSS and CSRF each need their own defenses.

Summary

  • XSS happens when untrusted data reaches a sink that parses it as HTML or code; choose textContent and DOM methods to avoid sinks.
  • Escaping fits only the context it was written for; validate URL schemes with new URL() and an allowlist.
  • To allow some HTML, sanitize with an allowlist using an inert DOMParser document, preferably with a maintained library or the Sanitizer API.
  • CSP is a safety net that blocks inline scripts and handlers if something slips through.
  • CSRF abuses automatic cookie sending; defend with SameSite cookies, anti-CSRF tokens and GET requests that never change state.
  • XSS defeats CSRF tokens, so you need both defenses.

Next: Dates and Times - working with moments in time, formatting and time zones.