# 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.

Published 2026-11-20 · Language: en · Tags: security, xss

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

 

```js
// 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.

 

```text
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.

 

## Cookie hardening

 

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.

Source: https://tdphat.io.vn/blog/xss-output-encoding-and-content-security-policy
