← Back to Baseline

Why it Matters

When variables are inserted directly into JavaScript blocks without escaping, attackers can inject scripts (XSS). This allows them to steal session cookies, run malicious code in the user’s browser, or change how the page works.

Escaping values in JavaScript context ensures that user-controlled data is treated as plain text instead of executable code. Magento provides safe functions like escapeJs() or using json_encode() to output structured data. This prevents script injection and protects customers and admins.

Verification Steps

Manual

# Search PHTML templates for variables inside <script> tags
grep -R "<script" app/design app/code

# Check if variables are escaped with:
$block->escapeJs($var)
json_encode($var)

Remediation / Fix Guidance

  1. Never insert raw PHP variables directly into <script> blocks.
  2. Use $block->escapeJs() for simple values like strings.
  3. For arrays or objects, output them using json_encode() so they are valid JSON.
  4. Review custom templates and themes for unsafe JavaScript injection.

Examples

Fail Example
<script>
   var name = "<?= $_GET['name'] ?>";
</script>
# Unsafe, attacker can inject "alert(1)" or worse
Pass Example
<script>
   var name = "<?= $block->escapeJs($_GET['name']) ?>";
</script>

<script>
   var config = <?= json_encode($data) ?>;
</script>
# Safe, variables are escaped or JSON-encoded

References