Cross-site scripting (XSS) is a web vulnerability that lets an attacker inject malicious JavaScript into pages that other users see, so the script runs in their browsers with the site’s privileges.
How XSS works
XSS happens when a website puts untrusted data into a page without proper encoding. The browser cannot tell the injected code from the site’s own JavaScript and executes it. There are three main types:
- Stored XSS – the payload is saved on the server, for example in a comment or profile, and hits every visitor.
- Reflected XSS – the payload sits in a link and is echoed back in the response; the victim must open the crafted URL.
- DOM-based XSS – the flaw is in client-side code that writes unsafe data into the page.
Why XSS matters for security
A running script can steal session cookies and tokens, perform actions as the user, show fake login forms, redirect to malware or modify page content. In 2005 the “Samy” worm used stored XSS to add over a million friends on MySpace within a day. Today XSS in admin panels, webmail and plugins for popular CMS remains a common way to take over accounts and websites. XSS and SQL injection both belong to the injection family of vulnerabilities.
How to prevent XSS
- Encode output according to context (HTML, attribute, JavaScript, URL); modern frameworks do this by default – do not bypass it.
- Sanitize user-supplied HTML with a proven library such as DOMPurify.
- Deploy a strict Content Security Policy (CSP) that blocks inline and third-party scripts.
- Mark session cookies as HttpOnly and Secure, and keep CMS plugins up to date.