Understanding Cross-Site Scripting (XSS)

Understanding Cross-Site Scripting (XSS)

Date: Feb 08, 2026

Category: Web Security

What is XSS?

Cross-Site Scripting (XSS) is a vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. This bypasses the Same Origin Policy (SOP).

Types of XSS

1. Reflected XSS

The malicious script comes from the current HTTP request.

  • Example: Search bars that echo the input without sanitization.
  • Impact: Session hijacking, phishing.

2. Stored XSS

The malicious script is stored on the target server (database, forum post, comment field).

  • Example: A comment on a blog that contains <script>alert(1)</script>.
  • Impact: Persistent attack on anyone who views the page.

3. DOM-based XSS

The vulnerability exists in client-side code rather than server-side code.

Prevention

1. Input Validation: Validate everything on arrival.

2. Output Encoding: Encode data before rendering it to the browser.

3. Content Security Policy (CSP): Restrict the sources of executable scripts.


// BAD
document.body.innerHTML = userInput;

// GOOD
document.body.innerText = userInput;

← All writing