Senior6 questionsFull Guide

Frontend Security (XSS, CSRF, CSP) — System Design Interview Guide

Master XSS, CSRF, CSP, clickjacking, and token security. Understand attack vectors, prevention strategies, and security headers. Frontend security appears far more often in interviews than most developers expect — this guide covers everything.

The Mental Model

Frontend security is about controlling what runs on your page (XSS), controlling what your browser sends automatically (CSRF), and controlling what your page can do (CSP). XSS injects malicious code into your page. CSRF tricks your browser into sending authenticated requests to another site. CSP is a whitelist that tells the browser which sources are allowed to run scripts, load images, and connect to APIs — even if an attacker injects code, CSP can block it from executing.

The Explanation

XSS — Cross-Site Scripting

XSS occurs when an attacker injects executable JavaScript into your page, which runs in other users' browsers in your site's context — with access to cookies, localStorage, DOM, and the ability to make requests as the victim.

The Three Types

  • Stored XSS: malicious script saved in the database (comment, username) and rendered for other users.
  • Reflected XSS: malicious script in a URL parameter, reflected immediately in the response.
  • DOM-based XSS: malicious script injected via client-side JS that writes to the DOM (innerHTML, document.write, eval).
// Vulnerable — sets innerHTML from URL param
const name = new URLSearchParams(location.search).get('name');
document.getElementById('greeting').innerHTML = 'Hello ' + name;
// Attack URL: /page?name=<img src=x onerror="stealCookies()">

// Safe — textContent doesn't parse HTML
document.getElementById('greeting').textContent = 'Hello ' + name;

Prevention

  • Always use textContent over innerHTML for user-controlled content
  • React's JSX auto-escapes by default — dangerouslySetInnerHTML opts out
  • Sanitize HTML with DOMPurify before any innerHTML assignment
  • Set httpOnly on session cookies — XSS can't steal what JS can't read

CSRF — Cross-Site Request Forgery

CSRF tricks a logged-in user's browser into sending an authenticated request to your server from a malicious page. Since the browser automatically attaches cookies to same-domain requests, the server can't tell the legitimate request from the forged one.

<!-- Attacker's page -- victim visits this while logged into bank.com -->
<img src="https://bank.com/transfer?to=attacker&amount=1000" />
<!-- Browser sends GET with bank.com cookies — authenticated by accident -->

Prevention

  • CSRF tokens: server generates a random token per session; client includes it in forms and AJAX headers; server validates it. Attacker's page cannot read the token (same-origin policy).
  • SameSite cookie attribute: SameSite=Strict — cookies not sent on any cross-site request. SameSite=Lax — sent on top-level navigations (links), not on forms or sub-requests. Both prevent CSRF for most cases.
  • Modern APIs: use Authorization: Bearer <token> header instead of cookies — custom headers can't be sent in CSRF attacks.

CSP — Content Security Policy

CSP is an HTTP header that whitelists which sources are trusted to load scripts, styles, images, and make connections. Even if an attacker injects a script tag, CSP prevents it from executing if the source isn't whitelisted.

# Strong CSP header
Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://cdn.trusted.com;
  style-src 'self' 'unsafe-inline';  # unsafe-inline should be avoided
  img-src 'self' data: https:;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';  # prevents clickjacking

frame-ancestors 'none' is the CSP equivalent of the X-Frame-Options header — prevents your page from being embedded in iframes (clickjacking protection).

Clickjacking

An attacker loads your site in a transparent iframe on their page and tricks users into clicking elements they can't see. Protection: X-Frame-Options: DENY or Content-Security-Policy: frame-ancestors 'none'.

Key Security Headers

Content-Security-Policy: default-src 'self'; script-src 'self'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()

Common Misconceptions

⚠️

HTTPS prevents XSS — HTTPS encrypts the transmission but doesn't prevent malicious scripts in your own page's content. XSS runs in your origin, not from a network interception.

⚠️

React is XSS-proof — React escapes JSX output, but dangerouslySetInnerHTML, eval(), and direct DOM manipulation bypass this. React apps can still have XSS vulnerabilities.

⚠️

CSRF only affects form submissions — CSRF can use img tags, script tags, fetch with cookies, and any request the browser makes automatically with credentials.

⚠️

CSP with 'unsafe-inline' still helps — 'unsafe-inline' completely defeats the purpose of CSP for script injection. Use nonces or hashes instead if inline scripts are unavoidable.

Where You'll See This in Real Code

GitHub: strict CSP prevents script injection; all user content (README, comments) rendered through a sanitization pipeline that strips dangerous HTML

Banking apps: double-submit CSRF tokens on all state-changing requests; SameSite=Strict cookies; short session expiry

Intercom, Zendesk widgets: loaded via script tags from CDN with SRI (Subresource Integrity) hash — browser verifies the file hasn't been tampered with

Large SaaS platforms (Notion, Figma): use nonce-based CSP — each page load generates a random nonce; only scripts with that nonce in the script tag are executed

Interview Cheat Sheet

  • XSS: use textContent not innerHTML; React JSX escapes by default; sanitize with DOMPurify for rich text
  • CSRF: SameSite=Strict/Lax cookies; CSRF tokens in headers; use Authorization header (not cookies) for APIs
  • CSP: whitelist script/style/connect sources; frame-ancestors 'none' stops clickjacking
  • httpOnly cookie: JS can't read it — protects tokens from XSS theft
  • Secure cookie: only sent over HTTPS
  • HSTS: forces HTTPS for all future visits (Strict-Transport-Security)
  • SRI (Subresource Integrity): integrity='sha256-...' on script/link tags — verifies CDN files haven't changed
  • X-Content-Type-Options: nosniff — prevents MIME type sniffing attacks
💡

How to Answer in an Interview

  • 1.Explain XSS with a concrete example — the innerHTML from URL params example is clear and memorable
  • 2.The token storage answer (httpOnly cookie > localStorage) connects XSS to authentication architecture — shows cross-topic depth
  • 3.CSRF and SameSite cookies — know the difference between Strict (breaks OAuth), Lax (default in modern browsers), and None (requires Secure, allows cross-site)
  • 4.CSP nonces are the gold standard — mention them for senior-level positions: 'each page load generates a cryptographic nonce; only inline scripts with that nonce execute'

Practice Questions

6 questions
#01

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

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

What is CSRF and how do SameSite cookies and CSRF tokens prevent it?

EasyFrontend Security PRO💡 Forged cross-origin request that rides on the victim's cookies — SameSite blocks cookie sending; CSRF token requires secret the attacker doesn't have
#03

What is a Content Security Policy (CSP) and how does it work?

EasyFrontend Security PRO💡 HTTP header that whitelists sources for scripts, styles, images — blocks injected inline scripts and unknown CDNs
#04

What is clickjacking and how do you prevent it?

EasyFrontend Security PRO💡 Attacker overlays your page in a transparent iframe — victim clicks on attacker UI but triggers your authenticated actions; prevent with frame-ancestors CSP
#05

What security HTTP response headers should every production frontend set?

EasyFrontend Security PRO💡 X-Content-Type-Options, X-Frame-Options/CSP frame-ancestors, HSTS, Referrer-Policy, Permissions-Policy
#06

How do you protect a frontend app against dependency supply chain attacks?

MediumFrontend Security PRO💡 Lock file, Subresource Integrity, audit CI, minimal dependencies, private registry proxying

Related Topics

Authentication Architecture (JWT, Cookies, SSO) — System Design Interview Guide
Senior·10–15 Qs
🎯

Can you answer these under pressure?

Reading answers is not the same as knowing them. Practice saying them out loud with AI feedback — that's what builds real interview confidence.

Practice Free →Try Output Quiz