Course contentsShow
← Security
Lesson 1220 of 3,05225. Application Security - Secure CodingFree lesson

Context-Specific Output Encoding

Learning to identify and apply the correct encoding for HTML, JavaScript, URL, CSS, and SQL contexts.

Context-Specific Output Encoding

What you'll learn: How to apply the right encoding technique based on where untrusted data appears in your output—HTML, JavaScript, URLs, CSS, or SQL.

Why One Encoding Doesn't Fit All

You've learned that output encoding is your last line of defense when untrusted data flows into your application. But here's the critical insight: the same dangerous string requires different encoding depending on where it lands.

Think of it like electrical adapters—the plug shape you need changes by country. Similarly, the encoding you need changes by context.

The Five Critical Contexts

HTML Context – Data between tags or in attributes:

  • Encode <, >, &, ", ' to HTML entities
  • Example: <div> becomes &lt;div&gt;

JavaScript Context – Data inside <script> tags or event handlers:

  • Escape quotes, backslashes, and control characters
  • Often requires JSON encoding or Unicode escaping

URL Context – Data in query strings or path segments:

  • Percent-encode special characters
  • Example: hello world becomes hello%20world

CSS Context – Data in style attributes or <style> blocks:

  • Escape with backslash-hex notation
  • Extremely restrictive; prefer allowlists

SQL Context – Data in database queries:

  • Use parameterized queries (not encoding!)
  • Or database-specific escaping if absolutely necessary

Why This Matters

If you HTML-encode data going into JavaScript, attackers can still inject code. If you URL-encode data going into HTML, it displays wrong and may still be vulnerable. Each context has unique parsing rules—you must match your encoding to the parser.

Key Takeaway: Always identify where untrusted data will be interpreted (HTML, JS, URL, CSS, SQL) and apply the encoding or escaping specific to that context—mismatched encoding leaves vulnerabilities wide open.