← Concepts

阅读中文版本

Output Encoding

Output encoding converts untrusted data into safe representation for the exact output context — HTML body, attribute, JavaScript string, URL — preventing it from being parsed as markup or code.

security

Definition

Output encoding is the systematic escaping of dynamic data at the point of interpolation, chosen by context: HTML entities for body text, attribute-safe quoting, JavaScript string escaping for script contexts, and URL encoding for href values. It is the primary XSS defense, complemented by CSP as a second layer.

Context and scope

Applied in every template and render path: HTML templates, client-side DOM construction, JSON embedded in script tags, and attribute interpolation.

Common misconceptions

  • Encoding once at input is enough — the safe encoding differs per output context; the same data may render into body, attribute, and script
  • Sanitization and encoding are interchangeable — sanitization removes dangerous markup from HTML input; encoding makes any data inert at output
  • Text nodes are the risky context — attribute, URL, and script contexts each have distinct escape sets and are frequently missed

Anti-patterns

  • Using one global escape function everywhere and corrupting or failing attribute and script contexts
  • Embedding JSON in script tags without encoding the closing-tag sequence
  • Building DOM via innerHTML with interpolated strings instead of textContent or createElement

Related concepts

Related examples

Authoritative source

https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

What it is

Injected code executes because the output parser cannot tell data from syntax. Encoding rewrites data bytes into forms that parsers read back as the original characters — the angle bracket becomes an entity, the quote becomes an escape — so data stays data in every context.

How it works

Contexts define the character set that matters: less-than in body, quotes in attributes, backslashes and script-tag closers in JavaScript strings, colons and slashes in URL attributes. Template engines provide per-context automatic escaping; raw interpolation opt-outs are where bugs concentrate. JSON-in-script needs a closing-script-tag guard in addition to string escaping.

When to apply

Every interpolation of untrusted or semi-trusted data. Prefer engines with context-aware auto-escaping, minimize raw modes, and lint against them in code review. DOM APIs — textContent, attribute assignment — encode by construction.

Pitfalls

Double encoding corrupts content; single correct-at-context encoding is the rule. Framework raw-mode escape hatches multiply over time — audit them as a class. Encoding does not sanitize rich HTML: for markup input, sanitize separately with an allowlist library.