How do you safely insert user content into an HTML page to prevent XSS?
Use your framework's default, context-aware output encoding so user data renders as text, never as markup — never concatenate raw input into HTML.
Unsafe (raw insertion):
<p>Welcome, ${username}!</p>
<!-- If username = <script>alert(1)</script>, XSS! -->
Safe (encoded output):
| Framework | Safe syntax | Unsafe (avoid!) |
|---|---|---|
| Blade (Laravel) | {{ $username }} |
{!! $username !!} |
| JSF | <h:outputText value="#{bean.name}" /> |
escape="false" |
| React | {username} (auto-escaped) |
dangerouslySetInnerHTML |
| Thymeleaf | th:text="${name}"` | `th:utext="${name}" |
Rule of thumb: The "safe by default" syntax handles encoding automatically. The "unsafe" variants exist for trusted HTML only (like CMS content from admins), never for user input.
If you must insert HTML: Use a sanitization library (e.g., DOMPurify for JavaScript, HTMLPurifier for PHP) to strip dangerous elements while keeping safe formatting.