Frontend

What XSS Is and How to Prevent It

The three main types of XSS, how the attack actually happens, its real-world impact, and why React's automatic escaping isn't the whole story.

Aref Busak
Aref BusakAuthor
2024-07-013 min read9 views
What XSS Is and How to Prevent It

What Is Cross-Site Scripting (XSS)?

OWASP defines XSS as an attack where malicious scripts get injected into an otherwise trusted website. Because the browser sees the code as coming from a site the user already trusts, it executes it without question — letting an attacker run arbitrary JavaScript exactly where the victim least expects it.

Three Main Types

Reflected XSS bounces the malicious input straight back in the same request/response cycle — for example, a URL parameter echoed unescaped into a search-results page. The victim has to click a crafted link.

Stored XSS persists the payload in a database, a comment field, or anywhere else, so it executes for every user who later views that content. It's more dangerous because the victim doesn't need to click anything special.

DOM-based XSS happens entirely client-side: the page's own JavaScript writes user-controlled data directly into the DOM without ever touching the server.

How It Happens

Common attack vectors include <script> tags, event-handler attributes like <img onerror=...>, and encoded URIs designed to slip past naive filters. The common thread is always the same: user input reaches HTML output without being escaped or validated.

Real-World Impact

A successful XSS attack can hijack cookies and sessions, take over accounts, deface page content, or redirect users into installing malware. On e-commerce or financial sites, that translates directly into stolen payment data or a broken trust relationship with users.

How to Prevent It

  • Output encoding — any user-supplied data rendered into HTML, JavaScript, or a URL needs to be escaped for that specific context.
  • Frameworks that are safe by default — React escapes everything you put inside JSX automatically. The real risk starts the moment you reach for dangerouslySetInnerHTML, which is exactly why this project only feeds it markdown that the admin themself writes, never untrusted visitor input.
  • Content Security Policy (CSP) — even if an injection slips through, a CSP can stop the browser from executing script from an unapproved source.
  • Input validation and sanitization — especially for any HTML that's meant to be rendered raw, like comments.

Takeaway

XSS is one of the oldest web vulnerabilities and still one of the most common, because any place unescaped user input reaches HTML is a potential opening. The strongest defense is relying on your framework's automatic escaping, avoiding raw HTML rendering wherever possible, and layering a CSP on top.

Source: OWASP — Cross-Site Scripting (XSS)

Frontend
Aref Busak
Aref Busak

Better web, better design — fast, modern, results-driven websites.