---
title: Avoid html_safe
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid html_safe
---

# Avoid html_safe

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `ruby-security/no-html-safe`

**Language:** Ruby

**Severity:** Warning

**Category:** Security

**CWE**: [79](https://cwe.mitre.org/data/definitions/79.html)

## Description{% #description %}

The `html_safe` method in Ruby on Rails marks a string as trusted and disables automatic HTML escaping. If any untrusted input is included, the output may contain raw HTML/JS and can lead to XSS. Thus, any use of `html_safe` on interpolated strings should be treated as unsafe **unless every interpolated value is known to be safe**.

This applies even if you are using `h` (also known as `html_escape`) because `h` does nothing if the string has already been marked `html_safe`.

Prefer letting Rails escape automatically:

```
<p><%= user_input %></p>
```

Or use tag helpers:

```rb
content_tag(:p, user_input)
tag.p(user_input)
```

When HTML is required, use `sanitize`:

```rb
content_tag(:p, sanitize(user_input))
```

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```ruby
# Unsafe unless `username` is trusted or explicitly escaped
page_content = "<p>hello, #{username}</p>".html_safe

# Unsafe unless you can prove `user_input` is not already marked `html_safe` (because `h` will not escape it).
page_content = "<p>description: #{h(user_input)}</p>".html_safe
```

## Compliant Code Examples{% #compliant-code-examples %}

```ruby
# For when HTML is required
content = content_tag(:p, sanitize(user_input))

# Tag helpers automatically perform escaping
content = content_tag(:p, "hello, #{username}")

# String literals are safe
content = "<p>hello</p>".html_safe
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 