Magento Security

How to Implement Proper Magento XSS Protection on Your Store

Updated on: May 2, 2022

How to Implement Proper Magento XSS Protection on Your Store

Cross-Site Scripting is a type of security vulnerability, which allows an attacker to run his/her scripts on your Magento store. In the absence of Magento XSS protection, the attacker can also accomplish a stored XSS attack. Thereafter, the malicious script will also run in the browsers of users visiting the infected page of your Magento store. In some cases, XSS can also be used to rewrite the HTML content of the page and therefore be used for phishing. According to hacking statistics, XSS constitutes about 40.8% of all vulnerabilities found in Magento between the year 2015 to 2019.

To protect your Magento store from such malicious attacks, proper Magento XSS protection measures should be in place. Today, with this article, we will explain the various symptoms of an XSS attack, possible causes, and a set of actionable Magento XSS protection techniques.

Symptoms of a Magento XSS Hack

In case of a Magento XSS hack, you may notice the following symptoms on your site:

  • Magento store users complain of account compromises or sudden password resets.
  • Automatic downloads of suspicious files when someone visits your Magento store.
  • Magento stores are being blacklisted by search engines like Google.
  • Users getting redirected to suspicious domains while visiting your Magento store.
  • Broken code appearing on your store’s page resembling some JavaScript or HTML code.
    Like the one shown in the following picture.

Infected website showing the appearance of broken code
Infected website showing the appearance of broken code
  • A site serving malicious advertisements or spammy content.
  • Fishy and unfamiliar customer accounts popping up

Unauthenticated customers added to the Magento store
Unauthenticated customers added to the Magento store
  • List of items and merchant payment options suddenly changing on your Magento store.

When the Magento stores are compromised due to a lack of Magento XSS protection, the users often ask for support on the help forums. See the picture below:

A screenshot of magento forum

Causes of a Magento XSS Hack

Although the prime cause of a Magento XSS hack is missing XSS protection. Some developers do not abide by safe coding practices, which in a way pave way for hackers. For instance, they do not sanitize user input. As a result, malicious users easily conduct an XSS attack.

Additionally, not escaping characters like “<” and “>” can also lead to an XSS hack.

In other cases, it may be a poorly coded Magento extension that you may be using for your store. These extensions frequently lack active development and security teams and are often poorly maintained. As a result, even though the Magento core is secure, your store can still be compromised.

In other cases, the Magento core itself has been found vulnerable to XSS attacks.

Magento XSS Hack Prevention

We saw the causes of a Magento XSS hack in the previous section. But the question is – how to avoid them? Well, there are certain proven ways that prevent XSS attacks on your Magento website.

Escaping is one of the techniques.

Escaping allows you to convert dangerous characters into their entity equivalents and prevent the execution of malicious code. In the case of Magento, an escaper class is available to sanitize the user input.

These methods should be used in the following scenarios:

Note: In all the cases, $ block is the local variable used for sanitization functions of escaper class.

1. JSON Inside HTML Attribute

Look at the source code of your Magento files and see if ‘JSON’ is present inside the HTML attribute like the one given in the code below:

<div data-bind='settings: <?=$myJson?>'></div>

If yes, sanitize it by using the escapeHTMLAttr() function of the Escaper class for Magento XSS protection as shown in the code below:

<div data-bind='settings: <?= $block->escapeHtmlAttr($myJson) ?>'></div>

2. HTML Inside the HTML Tag Content

Look at the source code of your Magento files and check if HTML is present inside the HTML content of any tag. The content of the <div> tag is provided below for your reference:

  <div id='my-element'>
      <?php echo 'Only registered users can write reviews. Please <a href="%1">Sign in</a> or <a href="%2">create an account</a>'?>

In such a case, use the escapeHTML() function as Magento XSS protection mechanism as demonstrated in the code below. Here, the <a> tag will be escaped.

  <div id='my-element'>
      <?php echo $block->escapeHtml(__('Only registered users can write reviews. Please <a href="%1">Sign in</a> or <a href="%2">create an account</a>', $block->getLoginUrl(), $block->getCreateAccountUrl()), ['a']) ?>

3. URL Inside Certain HTML Attributes

Look at the source code of your Magento files and see if URLs are present inside the HTML tags like the one given below:

<a href="<?=$url_string?;>">Click me</a>

If yes, then make sure to escape them using the escapeURL() method to ensure Magento XSS protection as shown in the code below:

<a href="<?= $block->escapeUrl($url_string) ?>">Click me</a>

4. JavaScript Inside HTML Attributes

Check the source code of your Magento files and see if javascript code is present inside HTML attributes like the one inside the attribute of<img> tag provided below:

<img src="images/title.png" onload="<?='<script>var_a=some_var;</script>';">

If yes, escape the javascript code using the escapeJs() function as shown in the provided code:

<img src="images/title.png"
    onload="<?= $block->escapeHtmlAttr('handler("' .$block->escapeJs($some_var) .'", ' .$block->escapeJs($var_a) .')') ?>">

Moreover, escape any HTML inside a javascript string or variable as shown in the code implementation below:

<script>                                                                          let phrase = "Hi, my name is <?= $block->escapeJs($myName) ?>";
let <?= $block->escapeJs($dynamicVariable) ?> = <?= $myJson ?>;

Also, ask your developers to label the elements whose properties may contain dynamic HTML with the “UnsanitizedHtml” suffix. This should be done as a precaution for Magento XSS protection. Here is a code to help you understand the same:

<div data-bind="html: propUnsanitizedHtml"></div>
<p html="returnUnsanitizedHtml()"></p>

To automatically check your Magento templates for XSS bugs, you can use this tool provided by Magento. To install it, follow this link. Once it is installed, open the terminal and run the following command to use it:

vendor/bin/phpcs --standard=Magento2 app/code/MyExten

Here, the coding standard is set to Magento 2 and the extension you wish to scan is inside the app/code/ folder named MyExten. Thereafter, this tool will scan the code of your Magento extension against a set of standard coding practices and notify you if there is a violation.


As seen in this article, XSS bugs are primarily caused due to unsafe coding practices. Moreover, there is no remedy for it except to write secure code and implementing Magento XSS protection. Average users might find it difficult to scan the code for Magento XSS vulnerabilities. But the same can be solved by opting for an in-depth Magento Security Audit and Pentesting program.

Astra offers a full-fledged Vulnerability Assessment and Penetration Testing program that detects and flags all underlying vulnerabilities on your website. The VAPT program checks the written code, extensions, modules, configurations, etc. for vulnerabilities and loopholes. This is how the Astra VAPT works:

Astra's VAPT process
Astra’s VAPT process

Have a question to ask? Contact us!

Was this post helpful?

Jinson Varghese

Jinson Varghese Behanan is an Information Security Analyst at Astra. Passionate about Cybersecurity from a young age, Jinson completed his Bachelor's degree in Computer Security from Northumbria University. When he isn’t glued to a computer screen, he spends his time reading InfoSec materials, playing basketball, learning French and traveling. You can follow him on Medium or visit his Website for more stories about the various Security Audits he does and the crazy vulnerabilities he finds.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments

Psst! Hi there. We’re Astra.

We make security simple and hassle-free for thousands
of websites and businesses worldwide.

Our suite of security products include a vulnerability scanner, firewall, malware scanner and pentests to protect your site from the evil forces on the internet, even when you sleep.

earth spiders cards bugs spiders

Made with ❤️ in USA France India Germany