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
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:
element.textContent = userInput;or
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:
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
| Problem | Cause | Safe solution |
|---|---|---|
innerHTML executes code | The inserted HTML is parsed and run by the browser | Use textContent |
A user can inject <script> or onerror | The browser trusts innerHTML | Use DOMPurify or server-side sanitization |
| XSS = full control over the page | The attack runs in the context of your domain | Validate and escape all user data |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.