Skip to main content

Security and innerHTML

Using innerHTML with user-supplied data is unsafe, because it can lead to an XSS vulnerability (Cross-Site Scripting). Let's break it down.


What happens

When you assign something to innerHTML, the browser interprets the string as HTML code and executes everything in it - including <script> tags, event attributes (onerror, onclick), and even inline JS.

An example of dangerous code

javascript
const comment = '<img src=x onerror="alert(`Hacked!`)">'; document.querySelector('#comments').innerHTML = comment;

Result:

  • An image appears on the page (which fails to load),
  • alert('Hacked!') runs,
  • And an attacker could have sent your user's cookies to their own server instead of showing an alert.

What XSS is

XSS (Cross-Site Scripting) is a type of attack where an attacker injects JavaScript code into your page, and the browser executes it in the context of your site.

This gives the hacker the ability to:

  • steal cookies (including the authorization token),
  • replace the page's content,
  • add fake forms to steal data,
  • perform actions on behalf of the user (for example, buy a product, send a message, etc.).

How to protect against it

1. Never insert user input through innerHTML

If you only need to display text, use:

javascript
element.textContent = userInput;

or

javascript
element.innerText = userInput;

They escape HTML, turning tags into plain text.


2. If you need HTML, use safe sanitization

If you still need to display HTML (for example, from a moderator or a trusted source) - pass the text through a library for sanitizing HTML, for example:

javascript
import DOMPurify from 'dompurify'; const safeHTML = DOMPurify.sanitize(userInput); element.innerHTML = safeHTML;

3. Also validate and escape on the server

Filter input, especially in forms and comments. XSS can also be stored (saved to the database, then displayed on a page).


Summary

ProblemCauseSafe solution
innerHTML executes codeThe inserted HTML is parsed and run by the browserUse textContent
A user can inject <script> or onerrorThe browser trusts innerHTMLUse DOMPurify or server-side sanitization
XSS = full control over the pageThe attack runs in the context of your domainValidate and escape all user data

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.