Sobes.tech
Senior

What security issues are associated with using innerHTML for inserting user input?

sobes.tech AI

Answer from AI

Using innerHTML to insert user input poses serious security risks, primarily related to XSS attacks (cross-site scripting). If user input is directly inserted into the DOM via innerHTML without proper sanitization or escaping, an attacker can inject malicious JavaScript code.

Example of the problem:

const userInput = '<img src=x onerror=alert("XSS")>';
document.getElementById('output').innerHTML = userInput;

As a result, an alert will execute on the page, demonstrating XSS.

To avoid this:

  • Never insert raw user input via innerHTML.
  • Use methods that insert text, not HTML, such as textContent.
  • If HTML needs to be inserted, use libraries for safe sanitization (e.g., DOMPurify).

Thus, innerHTML without filtering opens the door to executing malicious code, which can lead to data theft, session hijacking, and other attacks.

What security issues are associated with using… - sobes.tech