Back to all terms
Securityintermediate

Output Encoding

The process of converting untrusted data into a safe representation before rendering it in a specific output context.

Also known as: output escaping, contextual encoding, HTML encoding, entity encoding

Description

Output encoding is the practice of transforming data into a safe representation appropriate for the context in which it will be rendered. Unlike input validation, which operates at the entry point, output encoding operates at the exit point -- right before data is written to HTML, JavaScript, CSS, URLs, or other output contexts. This is a critical defense against XSS because even validated data may contain characters that are harmless in storage but dangerous in a specific rendering context.

The key principle is context-aware encoding: the same data requires different encoding depending on where it appears. In HTML body content, characters like <, >, and & must be entity-encoded. In HTML attribute values, additional characters like quotes must be escaped. In JavaScript string contexts, backslashes and quotes need escaping. In URL parameters, special characters must be percent-encoded. In CSS contexts, yet another encoding scheme applies. Using the wrong encoding for a context leaves the application vulnerable.

Modern frontend frameworks like React, Angular, Vue, and Svelte apply automatic output encoding by default, which dramatically reduces XSS risk. However, developers must understand when they are bypassing this protection (dangerouslySetInnerHTML in React, v-html in Vue, [innerHTML] in Angular) and ensure manual encoding is applied in those cases. Server-side template engines should also be configured for auto-escaping, and any raw output modes should be audited carefully.

Prompt Snippet

Apply context-specific output encoding at every rendering boundary: use HTML entity encoding (he.encode() or built-in framework escaping) for HTML body content, encodeURIComponent() for URL parameters, JSON.stringify() for data embedded in script contexts, and CSS.escape() for CSS values. Rely on React's JSX auto-escaping by default and audit all uses of dangerouslySetInnerHTML or equivalent bypass APIs (v-html, bypassSecurityTrustHtml). For server-rendered templates (EJS, Handlebars, Pug), ensure auto-escaping is enabled and use raw output syntax ({{{ }}}) only with DOMPurify-sanitized content.

Tags

encodingescapingxss-preventioncontext-aware-security