
In mid-level and senior frontend engineering interviews, security questions rarely stop at textbook definitions of the Same-Origin Policy. Instead, hiring panels present a breaking production incident: "Your team just moved the authenticated dashboard from app.example.com onto a dedicated API subdomain api.example.com. In staging everything worked, yet in production half of user PATCH requests fail with a browser CORS error, a CDN edge node is caching the wrong Access-Control-Allow-Origin header, and a support widget using dangerouslySetInnerHTML just triggered an alert from a security scan. Walk through what failed and how you fix each layer."
Candidates who guess "set Access-Control-Allow-Origin: *" or "use HttpOnly cookies so XSS cannot steal sessions" miss the exact browser security invariants panels test in web security cors xss csrf frontend interview loops. Understanding how browser origin boundaries interact with HTTP headers, DOM sinks, and ambient cookie credentials is a core pillar of any complete technical interview preparation roadmap.
This guide breaks down the threat models behind CORS, XSS, and CSRF, walks through three real-world production debugging scenarios with exact code and header fixes, and provides the scoring rubric interviewers use to separate senior frontend engineers from surface-level memorization.
The Browser Threat Model: CORS vs. XSS vs. CSRF
Before debugging headers or sanitizers, interviewers expect candidates to distinguish who is attacking whom and what browser guarantee each mechanism protects. Confusing CORS (an intentional relaxation of the Same-Origin Policy) with CSRF (an attack that exploits ambient credentials across origins) is one of the fastest ways to lose points in frontend security interview questions.

Use this comparison table when framing your architectural defense in live interviews:
| Security Mechanism | Core Threat / Boundary | What Actually Runs or Fails | Primary Production Defense | Common Interview Misconception |
|---|---|---|---|---|
| CORS (Cross-Origin Resource Sharing) | Controls whether Origin A JavaScript can read responses from Origin B | Browser blocks response access or rejects preflight OPTIONS before sending unsafe requests | Explicit Access-Control-Allow-Origin allowlist, Vary: Origin, and matching Access-Control-Allow-Credentials: true | Believing CORS blocks requests on the server; non-browser tools like curl ignore CORS completely |
| XSS (Cross-Site Scripting) | Attacker injects executable JavaScript inside your trusted origin | Malicious script reads DOM, exfiltrates tokens, or issues authenticated actions as the victim | Contextual output encoding, strict DOMPurify sanitization, and Content-Security-Policy (nonce + strict-dynamic) | Assuming HttpOnly cookies neutralize XSS; an XSS payload can still invoke fetch() with cookies attached |
| CSRF (Cross-Site Request Forgery) | Malicious site tricks a logged-in browser into sending state-changing requests | Browser automatically attaches session cookies on cross-site forms or fetch() calls | SameSite=Lax or Strict cookies, anti-CSRF tokens, custom headers, and Sec-Fetch-Site validation | Relying solely on CORS to stop CSRF; simple HTML <form> POST requests execute without a CORS preflight |
For a broader refresher on how HTTP fundamentals, DOM APIs, and event propagation fit into browser architecture rounds, review these core HTML, CSS, and JavaScript frontend interview questions.
Production Failure #1: Debugging a Broken CORS Preflight and CDN Cache
Returning to the opening subdomain migration incident: why did PATCH requests fail in production while GET requests passed intermittently, and why did the CDN serve mismatched headers?
Why Simple Requests Differ from Preflighted Requests
A browser only skips the preflight OPTIONS check for simple requests (GET, HEAD, or POST with application/x-www-form-urlencoded, multipart/form-data, or text/plain, and no custom headers like Authorization or X-CSRF-Token). Sending a PATCH request or Content-Type: application/json forces the browser to send an unauthenticated OPTIONS preflight first.
Two production traps cause immediate outages during subdomain splits:
- Wildcard Origin with
credentials: "include": When frontend code sends session cookies cross-origin usingfetch(url, { credentials: "include" }), the CORS specification forbidsAccess-Control-Allow-Origin: *. The server must echo the exact validated origin (https://app.example.com) alongsideAccess-Control-Allow-Credentials: true. - Missing
Vary: Originon Edge Caches: If an API server dynamically reflects theOriginheader (https://app.example.comorhttps://admin.example.com) without returningVary: Origin, a CDN or reverse proxy caches the first response'sAccess-Control-Allow-Originheader and serves it to the second origin—causing sporadic CORS errors that disappear whenever caches expire.
Fixing the Server CORS Middleware
const ALLOWED_ORIGINS = new Set([
"https://app.example.com",
"https://admin.example.com",
]);
export function corsMiddleware(req, res, next) {
const origin = req.headers.origin;
// Always tell CDNs and proxies that response headers depend on Origin
res.setHeader("Vary", "Origin");
if (origin && ALLOWED_ORIGINS.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, X-CSRF-Token"
);
// Cache preflight result in the browser for 10 minutes to cut OPTIONS traffic
res.setHeader("Access-Control-Max-Age", "600");
}
if (req.method === "OPTIONS") {
return res.status(204).end();
}
return next();
}
Notice two subtle points interviewers probe here: first, never reflect arbitrary req.headers.origin values or use naive substring checks like origin.endsWith("example.com") (which evil-example.com bypasses). Second, preflight OPTIONS requests do not include cookies, so authentication middleware must never reject OPTIONS with 401 Unauthorized before the CORS handler runs. Teams coordinating multi-app deployments across subdomains encounter this pattern frequently—see our breakdown of cross-app isolation in micro frontends architecture trade-offs as well as backend API gateway patterns in REST API interview questions and answers.
Production Failure #2: Eliminating DOM XSS with Sanitization and CSP Nonces
In modern single-page applications, frameworks like React automatically escape text interpolated into JSX (<div>{userComment}</div>), which prevents classic HTML injection. However, DOM-based XSS and Stored XSS still surface whenever code bypasses framework escaping via dangerouslySetInnerHTML, element.innerHTML, dynamic href="javascript:..." links, or third-party markdown renderers.
Why HttpOnly Cookies Do Not Stop XSS
A frequent wrong answer in web security cors xss csrf frontend interview discussions is claiming "XSS is mitigated because our JWT is in an HttpOnly cookie." While HttpOnly prevents document.cookie from exposing the raw token, an attacker running JavaScript inside your origin already executes with the user's authenticated session. The script can silently issue fetch("/api/account/email", { method: "PATCH", credentials: "include", ... }), hijack the account, or exfiltrate sensitive API responses rendered in the DOM.
Defense-in-Depth: DOMPurify, Protocol Allowlists, and Strict CSP
A production-grade fix pairs sink sanitization with a strict Content Security Policy (CSP):
import DOMPurify from "dompurify";
function sanitizeSafeUrl(rawUrl) {
try {
const parsed = new URL(rawUrl, window.location.origin);
return parsed.protocol === "https:" || parsed.protocol === "http:"
? parsed.href
: "#";
} catch {
return "#";
}
}
export function SupportArticleCard({ rawHtml, externalLink }) {
// Strip <script>, onerror handlers, and SVG script payloads before DOM insertion
const cleanHtml = DOMPurify.sanitize(rawHtml, {
ALLOWED_TAGS: ["b", "i", "em", "strong", "p", "ul", "li", "code"],
ALLOWED_ATTR: [],
});
return (
<article>
<div dangerouslySetInnerHTML={{ __html: cleanHtml }} />
<a href={sanitizeSafeUrl(externalLink)} rel="noopener noreferrer">
Read documentation
</a>
</article>
);
}
At the HTTP response layer, pair sanitization with a nonce-based CSP rather than allowlisting broad CDNs or using 'unsafe-inline':
Content-Security-Policy:
default-src 'self';
script-src 'nonce-r4nd0mPerRequestToken' 'strict-dynamic';
object-src 'none';
base-uri 'none';
frame-ancestors 'none';
In this policy:
'nonce-...'ensures only<script nonce="r4nd0mPerRequestToken">tags generated by your server per HTTP request can execute, blocking injected inline scripts and event handlers (<img onerror="...">).'strict-dynamic'allows trusted nonced bootstrap scripts to load verified downstream bundles without maintaining fragile host allowlists.base-uri 'none'prevents attackers from injecting a<base href="https://evil.test/">tag to hijack relative script URLs, whileframe-ancestors 'none'stops clickjacking.
For more React-specific rendering and security pitfalls covered in frontend loops, check our React interview questions guide.
Production Failure #3: Stopping CSRF Beyond SameSite=Lax

Modern browsers default cookies without an explicit SameSite attribute to SameSite=Lax, which blocks cookies on cross-site POST forms and fetch() requests while allowing them on top-level GET navigations. Many candidates assume CSRF is therefore "solved automatically." Senior interviewers quickly test the three cracks in that assumption:
- State-Changing
GETEndpoints: If an endpoint likeGET /api/projects/delete?id=42mutates state,SameSite=Laxwill attach the cookie when a victim clicks a link or loads a top-level redirect from another site. - Sibling Subdomain Compromise: Cookies are scoped by site (eTLD+1, e.g.,
example.com), not origin (sub.example.com). A vulnerable legacy blog onblog.example.comis considered same-site toapi.example.com, meaningSameSite=StrictorSameSite=Laxcookies still travel across subdomains. - Cross-Site Embedded Flows (
SameSite=None): Payment widgets, OAuth embeds, or third-party integrations requiringSameSite=None; Securestrip awaySameSiteprotection completely.
Layered CSRF Prevention: Tokens + Fetch Metadata
Production systems combine anti-CSRF tokens (synchronizer token or double-submit signed token), non-simple custom headers, and Sec-Fetch-Site Fetch Metadata validation:
export function csrfProtection(req, res, next) {
// Only enforce on state-changing HTTP methods
if (["GET", "HEAD", "OPTIONS"].includes(req.method)) {
return next();
}
// Layer 1: Reject explicit cross-site requests via browser Fetch Metadata
const fetchSite = req.headers["sec-fetch-site"];
if (fetchSite && !["same-origin", "same-site", "none"].includes(fetchSite)) {
return res.status(403).json({ error: "Cross-site request blocked" });
}
// Layer 2: Verify CSRF token (cannot be forged by simple HTML forms)
const headerToken = req.headers["x-csrf-token"];
const sessionToken = req.session?.csrfToken;
if (!headerToken || !sessionToken || headerToken !== sessionToken) {
return res.status(403).json({ error: "Invalid or missing CSRF token" });
}
return next();
}
Why does requiring an X-CSRF-Token header work alongside token matching? Even if an attacker submits a hidden <form> from evil.test, HTML forms cannot attach custom HTTP headers—and any cross-origin fetch() attempting to set X-CSRF-Token triggers a CORS OPTIONS preflight that your strict origin allowlist rejects. Notice also that in production you should compare secrets using a constant-time comparison such as crypto.timingSafeEqual to eliminate timing side channels.
Live Code Review Walkthrough: Spot the Three Security Bugs
Interviewers frequently hand candidates a compact full-stack snippet and ask them to find every vulnerability within two minutes. Review this 18-line example:
// Backend (Express)
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", req.headers.origin || "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
next();
});
app.get("/api/billing/cancel", (req, res) => {
cancelSubscription(req.user.id);
res.send(`<div>Cancelled plan for ${req.query.reason}</div>`);
});
A strong candidate immediately catches three distinct defects:
- Arbitrary Origin Reflection with Credentials: Echoing
req.headers.origindirectly intoAccess-Control-Allow-OriginalongsideAccess-Control-Allow-Credentials: truelets any malicious domain issue credentialedfetch()calls and read private API responses—completely defeating the Same-Origin Policy. Fix this with an explicitALLOWED_ORIGINSset andVary: Origin. - State Mutation Over
GET(CSRF Vector): Canceling a subscription on aGEThandler allows any third-party site to trigger cancellation via an<img src="https://api.example.com/api/billing/cancel">or top-level link, bypassingSameSite=Lax. Move mutations exclusively toPOST/DELETEwith CSRF token andSec-Fetch-Siteverification. - Reflected XSS via Unescaped Query Parameter: Interpolating
req.query.reasondirectly into HTML lets?reason=<script>...</script>execute arbitrary code on the API origin. Return JSON (res.json(...)) withContent-Type: application/jsonandX-Content-Type-Options: nosniff, or HTML-encode untrusted input before rendering.
Web Security Interview Scoring Rubric
Hiring panels evaluate how cleanly candidates connect browser specifications to real operational fixes—a signal emphasized in what interviewers actually look for. Compare weak signals against senior-level engineering answers:
| Evaluation Dimension | Weak / Red-Flag Signal | Strong / Senior Hire Signal |
|---|---|---|
| Same-Origin Policy & CORS | Claims CORS protects servers from malicious API calls or recommends Access-Control-Allow-Origin: * with cookies | Explains preflight triggers, exact origin allowlists, Access-Control-Allow-Credentials: true, and Vary: Origin CDN caching |
| XSS & CSP Strategy | Relies solely on HttpOnly cookies or suggests regex stripping of <script> tags | Separates React JSX escaping from DOM sinks, uses DOMPurify + URL protocol checks, and configures nonce-based CSP with strict-dynamic |
| CSRF Defense Depth | Assumes SameSite=Lax eliminates all CSRF risk without checking HTTP methods or subdomains | Protects state-changing routes with POST/PATCH, synchronizer CSRF tokens, custom headers, and Sec-Fetch-Site validation |
| Incident Debugging | Guesses random header tweaks without checking DevTools Network tab or request lifecycle | Isolates preflight OPTIONS status, inspects response Vary and Set-Cookie flags, and traces where untrusted data enters a sink |
Practice Frontend Security Scenarios Under Time Pressure
Memorizing header names from documentation feels easy until an interviewer changes a single constraint—like moving an app onto a shared CDN or adding a subdomain widget—and asks what breaks first.
- Test Your Instincts in 60 Seconds: Launch the free 60-Second Job Blitz to drill rapid-fire frontend security, CORS, XSS, and browser architecture questions with zero login required.
- Simulate Realistic Live Follow-Ups: Paste your target Frontend or Full-Stack Engineer job description into totop.app, pair it with a structured 30-day technical interview prep schedule, and use the built-in Socratic Tutor to defend your CSP and CSRF architecture decisions out loud.
- Start Practicing Free: Claim 10 free AI interview practice tests or unlock unlimited voice and text mock interviews on the totop.app pricing page.
Practice Senior React Engineer Questions Live with AI Mock Interviews
Turn any job description across Engineering, DevOps, Data, Marketing, Sales, Finance, or HR into a personalized test and live voice or text AI mock interview on totop.app, or test your speed right now in the 60-Second Senior React Engineer Blitz.
Play 60s Senior React Engineer Blitz (Free, No Login) | Start 14-Day Free Trial | Browse All Interview Guides