erb ruby javascript 27 lines · 3 tabs

Cross site scripting defense with output encoding and CSP

Kai Nakamura Apr 2026
3 tabs
<h1><%= @post.title %></h1>
<p><%= @post.author_name %></p>

<%# Only sanitized rich text should be rendered as HTML %>
<div class="prose"><%= sanitize(@post.body_html, tags: %w[p a ul ol li strong em code], attributes: %w[href]) %></div>
3 files · erb, ruby, javascript Explain with highlit

XSS defense works best in layers: correct output encoding, sanitization for trusted rich text only, and a restrictive Content-Security-Policy. I avoid storing untrusted HTML unless there is a strong product reason. When rich content is required, I sanitize at write time and keep CSP strict enough to limit blast radius.

Share this code

Here's the card — post it anywhere.

Cross site scripting defense with output encoding and CSP — share card
Link copied