---
title: Context-Aware Output Escaping
impact: HIGH
impactDescription: prevents XSS by using correct encoding for different contexts
tags: security, xss, encoding, escaping
---

## Context-Aware Output Escaping

Escape data based on where it is displayed: HTML body, HTML attribute, JS variable, or CSS. Rails ERB handles HTML body escaping, but other contexts need specific helpers.

**Incorrect (incorrect context):**

```erb
<script>
  // Vulnerable to XSS if user.name contains quotes/backslashes
  var user_name = "<%= user.name %>";
</script>

<div onclick="alert('<%= user.name %>')">Click me</div>
```

**Correct (context-specific helpers):**

```erb
<script>
  // Use j (escape_javascript) or raw with to_json
  var user_name = <%= user.name.to_json.html_safe %>;
</script>

<%# Attribute escaping is handled by Rails tag helpers %>
<%= link_to "Profile", user_path(user), title: user.name %>
```

**Tools:** Brakeman, Rails default
---
