Cross-Site Scripting (XSS) is a type of security vulnerability typically found in web applications. It allows an attacker to inject malicious scripts (usually JavaScript) into web pages viewed by other users. Unlike many other web attacks that target the server directly, XSS targets the users of the website by exploiting the trust a browser has in the content sent by that server.
How XSS Works?
XSS occurs when an application includes untrusted data in a web page without proper validation or escaping. When an unsuspecting user visits the compromised page, their browser executes the malicious script, thinking it is a legitimate part of the website.
The Core Mechanism:
- Injection: The attacker finds an input field (like a comment section, search bar, or profile name) that doesn’t filter data correctly and submits a script.
- Storage/Execution: The website either stores that script in its database or reflects it back to the user in a URL.
- Victim Interaction: A victim visits the page. Their browser receives the script and executes it.
- Data Theft: The script can then steal session cookies, capture keystrokes, or redirect the user to a fraudulent site.

The Three Main Types of XSS
- Stored (Persistent): The script is permanently stored on the target server (e.g., in a database). Example: A malicious script hidden in a forum post that runs whenever someone views the thread.
- Reflected (Non-Persistent): The script is “reflected” off the web server via a link or a search result. Example: A link sent via email that includes a script in the URL parameter.
- DOM-based: The vulnerability exists entirely in the client-side code rather than the server-side code. Example: A script that modifies the Document Object Model (DOM) of the page to execute malicious code.
Why is It Dangerous?
Because the script runs in the context of the legitimate website, it can bypass the Same-Origin Policy. This gives attackers the power to:
- Steal Session Cookies: This allows them to hijack your login session and access your account without a password.
- Phishing: They can rewrite the HTML of the page to show a fake login form that sends your credentials to the attacker.
- Keylogging: Every keystroke you type on that page can be recorded.

How to Prevent XSS?
The golden rule of web security is: Never trust user input.
- Output Encoding: Convert special characters like < and > into HTML entities (< and >) so the browser treats them as text, not code.
- Input Validation: Use “allow-lists” to ensure only expected data formats (like numbers or dates) are accepted.
- Content Security Policy (CSP): A modern browser security layer that tells the browser which sources of scripts are trusted, effectively blocking most unauthorized scripts.




