EasyFrontend Security📖 Theory Question

What is XSS (Cross-Site Scripting) and how do you prevent it?

💡

Hint

Attacker injects script that runs in another user's browser — prevent by escaping output, using CSP, and never using innerHTML with user data

Full Answer

XSS occurs when an attacker injects malicious JavaScript into a page that is then executed in another user's browser, giving the attacker access to cookies, tokens, and the DOM.

Three types:

  • Stored XSS — malicious script is saved in the database (e.g., a comment) and served to every user who views it.
  • Reflected XSS — script is embedded in a URL, reflected in the response (e.g., search results page).
  • DOM-based XSS — client-side JS reads attacker-controlled data (URL hash, postMessage) and writes it to the DOM unsafely.

Prevention:

  • Never use innerHTML, dangerouslySetInnerHTML, or document.write with untrusted data. React auto-escapes by default — this is why it's safer.
  • Output encoding — HTML-encode user content before rendering it.
  • Content Security Policy (CSP) — restricts which scripts can execute; blocks inline scripts.
  • Sanitize HTML input — if you must allow rich text, use DOMPurify.
import DOMPurify from 'dompurify';
// Safe: sanitize before dangerouslySetInnerHTML
const clean = DOMPurify.sanitize(userHtml);
<div dangerouslySetInnerHTML={{ __html: clean }} />

More Frontend Security Questions

EasyWhat is CSRF and how do SameSite cookies and CSRF tokens prevent it?EasyWhat is a Content Security Policy (CSP) and how does it work?EasyWhat is clickjacking and how do you prevent it?EasyWhat security HTTP response headers should every production frontend set?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint