Skip to content

XSS Prevention: Encode for the Output Context

Cross-site scripting begins when untrusted data becomes executable content. Learn contextual encoding, safe DOM APIs and CSP defence in depth.

Muhammad Azhar August 14, 2026 Editorial date: November 7, 2026 2 min read

XSS occurs when untrusted data is interpreted as executable browser content. The correct defence depends on where data is inserted: HTML text, an attribute, a URL, CSS and JavaScript have different rules.

Prefer safe APIs

Use framework escaping and DOM properties such as textContent. Avoid building HTML strings from user data. When users genuinely need formatted HTML, apply a maintained sanitizer with a narrow allowlist.

Do not rely on input filtering alone

The same stored value may later appear in several output contexts. Encode at output for the actual context and validate input for business rules.

Add defence in depth

A nonce- or hash-based CSP can limit script execution if a bug remains. Mark session cookies HttpOnly, but remember XSS can still act through the victim's browser.

Test dangerous sinks

Review innerHTML, URL assignments, template escapes and client-side rendering after dependencies change.

URL handling needs protocol checks

Encoding a value does not make a dangerous javascript: URL safe. Parse and allow expected schemes before assigning user-controlled links. Treat SVG and rich-text uploads as active-content risks.

Framework escape hatches deserve review

Raw HTML APIs and template escape hatches can bypass normal escaping and need review. Trusted Types can instead enforce checks at covered DOM injection sinks; its policies still need suitable validation or sanitization.

Trace data from source to sink

Review URL parameters, stored fields, API responses, postMessage events and URL fragments. Stored XSS can execute later in an administrator screen; DOM XSS can arise without a server-rendered page.

Review error pages, previews, HTML emails and administrative tables as separate output contexts. Quote attributes and keep untrusted data out of executable JavaScript and CSS contexts where practical.

Test representative payloads in an isolated environment and verify that they render as inert text while legitimate rich content still works. Third-party scripts execute with the page's authority and need dependency review. Fixing one reflected alert does not establish that stored or DOM-based paths are safe.

Sources and further reading