Find Security Issue
Easy



Prompt
Can You Identify the Security Issue in This Code Snippet?
const data = await fetch(“api”);
const div = document.getElementById(“todo”);
div.innerHTML = data;
The Issue
This is perfect example of Cross-Site Scripting (XSS) attack. Let's break down the code to understand how it works.
- We fetch the data from the
api
endpoint. - We grab the div element from the DOM with the id
todo
. - We directly insert the API response into our HTML using innerHTML
The problem is that we're trusting the API data completely! If that data contains malicious JavaScript code like <script>stealUserData()</script>
or <img src="x" onerror="runMaliciousCode()">
, our application will happily insert it into the DOM and execute it.
Why is this dangerous?
When malicious code executes in your user's browser:
- It can steal authentication cookies
- It can access sensitive information on the page
- It can perform actions on behalf of the user
- It can modify the page content to trick the user
How can we fix it?
- Use
textContent
instead ofinnerHTML
to insert the data into the DOM - Use a library like
DOMPurify
to sanitize the data
const data = await fetch(“api”);
const div = document.getElementById(“todo”);
div.textContent = DOMPurify.sanitize(data);
Resources
DOMPurify
Why use textContent over innerHTML
00:00