Skip to content

Web security basics · Part 3 of 10

XSS: output encoding and Content Security Policy

Cross-site scripting runs an attacker's script in your users' browsers. Encode output by context and add a Content Security Policy as a second layer.

· 2 min read

securityxss

Cross-site scripting (XSS) lets an attacker make a victim's browser run their JavaScript on your site. That script can read what the user sees, act as the user and steal session data that is not protected.

Kinds of XSS

  • Stored: the malicious input is saved, for example in a comment, and shown to every visitor.
  • Reflected: input in a URL or form is echoed straight back in the response.
  • DOM-based: client-side code writes untrusted data into the page, for example through innerHTML.

The main defence: encode on output

Treat data as text unless you explicitly decided otherwise. Encode it for the place where it is inserted: HTML body, HTML attribute, JavaScript string, URL. Modern template engines escape HTML by default, so the danger is in the escape hatches such as raw, html_safe or dangerouslySetInnerHTML.

Ruby
require "cgi"

comment = "<script>alert(1)</script>"
puts CGI.escapeHTML(comment)   # &lt;script&gt;alert(1)&lt;/script&gt;

In the browser

JavaScript
// Safe: the value is treated as text.
element.textContent = userInput;

// Dangerous: the value is parsed as HTML.
// element.innerHTML = userInput;

If you must allow some HTML, such as rich comments, pass it through a well-maintained sanitiser with an allow-list of tags.

Content Security Policy

A CSP header tells the browser which sources of scripts, styles and other content are allowed. A strict policy blocks inline scripts and scripts from unknown origins, so an injected script often fails to run.

Code
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-RANDOM'; object-src 'none'; frame-ancestors 'none'

A nonce is a random value generated for each response and added to your own script tags. CSP is a second line of defence. It does not replace encoding.

Mark session cookies HttpOnly so scripts cannot read them, Secure so they travel only over HTTPS, and set SameSite.

Takeaway

Escape by context, avoid raw HTML insertion, sanitise rich input with an allow-list, and deploy a strict CSP and hardened cookies to limit the damage if something slips through.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.