Frontend engineer analyzing a blocked CORS OPTIONS preflight bridge in browser DevTools rendered in Risograph print style

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.

Three-column Risograph infographic comparing CORS OPTIONS preflight bridges, XSS CSP nonce filtering, and CSRF SameSite token locks

Use this comparison table when framing your architectural defense in live interviews:

Security MechanismCore Threat / BoundaryWhat Actually Runs or FailsPrimary Production DefenseCommon Interview Misconception
CORS (Cross-Origin Resource Sharing)Controls whether Origin A JavaScript can read responses from Origin BBrowser blocks response access or rejects preflight OPTIONS before sending unsafe requestsExplicit Access-Control-Allow-Origin allowlist, Vary: Origin, and matching Access-Control-Allow-Credentials: trueBelieving 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 originMalicious script reads DOM, exfiltrates tokens, or issues authenticated actions as the victimContextual 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 requestsBrowser automatically attaches session cookies on cross-site forms or fetch() callsSameSite=Lax or Strict cookies, anti-CSRF tokens, custom headers, and Sec-Fetch-Site validationRelying 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:

  1. Wildcard Origin with credentials: "include": When frontend code sends session cookies cross-origin using fetch(url, { credentials: "include" }), the CORS specification forbids Access-Control-Allow-Origin: *. The server must echo the exact validated origin (https://app.example.com) alongside Access-Control-Allow-Credentials: true.
  2. Missing Vary: Origin on Edge Caches: If an API server dynamically reflects the Origin header (https://app.example.com or https://admin.example.com) without returning Vary: Origin, a CDN or reverse proxy caches the first response's Access-Control-Allow-Origin header 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, while frame-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

Risograph conceptual still life of a CSP prism gate deflecting script darts beside an HttpOnly SameSite keycard and origin passport

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:

  1. State-Changing GET Endpoints: If an endpoint like GET /api/projects/delete?id=42 mutates state, SameSite=Lax will attach the cookie when a victim clicks a link or loads a top-level redirect from another site.
  2. Sibling Subdomain Compromise: Cookies are scoped by site (eTLD+1, e.g., example.com), not origin (sub.example.com). A vulnerable legacy blog on blog.example.com is considered same-site to api.example.com, meaning SameSite=Strict or SameSite=Lax cookies still travel across subdomains.
  3. Cross-Site Embedded Flows (SameSite=None): Payment widgets, OAuth embeds, or third-party integrations requiring SameSite=None; Secure strip away SameSite protection 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:

  1. Arbitrary Origin Reflection with Credentials: Echoing req.headers.origin directly into Access-Control-Allow-Origin alongside Access-Control-Allow-Credentials: true lets any malicious domain issue credentialed fetch() calls and read private API responses—completely defeating the Same-Origin Policy. Fix this with an explicit ALLOWED_ORIGINS set and Vary: Origin.
  2. State Mutation Over GET (CSRF Vector): Canceling a subscription on a GET handler allows any third-party site to trigger cancellation via an <img src="https://api.example.com/api/billing/cancel"> or top-level link, bypassing SameSite=Lax. Move mutations exclusively to POST/DELETE with CSRF token and Sec-Fetch-Site verification.
  3. Reflected XSS via Unescaped Query Parameter: Interpolating req.query.reason directly into HTML lets ?reason=<script>...</script> execute arbitrary code on the API origin. Return JSON (res.json(...)) with Content-Type: application/json and X-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 DimensionWeak / Red-Flag SignalStrong / Senior Hire Signal
Same-Origin Policy & CORSClaims CORS protects servers from malicious API calls or recommends Access-Control-Allow-Origin: * with cookiesExplains preflight triggers, exact origin allowlists, Access-Control-Allow-Credentials: true, and Vary: Origin CDN caching
XSS & CSP StrategyRelies solely on HttpOnly cookies or suggests regex stripping of <script> tagsSeparates React JSX escaping from DOM sinks, uses DOMPurify + URL protocol checks, and configures nonce-based CSP with strict-dynamic
CSRF Defense DepthAssumes SameSite=Lax eliminates all CSRF risk without checking HTTP methods or subdomainsProtects state-changing routes with POST/PATCH, synchronizer CSRF tokens, custom headers, and Sec-Fetch-Site validation
Incident DebuggingGuesses random header tweaks without checking DevTools Network tab or request lifecycleIsolates 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