Tech Interview RoomStudy guides

Browser & Performance

How do you protect a frontend from XSS and CSRF? Explain CSP and cookie flags.

Advanced · 2 min read · Lesson 7 of 8 in Browser & Performance

XSS (Cross-Site Scripting)

An attacker gets their script to run on your page, where it can steal tokens, act as the user or change the page.

  • Stored (saved in the database), reflected (from the URL), DOM-based (client code writes untrusted data into the DOM).
  • React and Vue escape text in {} and {{ }} automatically. Danger points: dangerouslySetInnerHTML, v-html, innerHTML, href={userUrl} with javascript: URLs, eval, and building HTML strings.
  • Sanitise any HTML you must render with DOMPurify. Validate URLs against http(s):.
  • Defence in depth: a strict Content Security Policy and Trusted Types (require-trusted-types-for 'script'), which make dangerous DOM sinks reject plain strings.

Content Security Policy

A response header listing what may load and run. A strict, nonce-based policy (script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'none') blocks injected inline scripts even when an XSS bug exists. frame-ancestors 'none' prevents clickjacking. Start with Content-Security-Policy-Report-Only to find breakages.

CSRF (Cross-Site Request Forgery)

Another site makes the user's browser send a request that automatically includes your cookies.

  • SameSite=Lax (the default in modern browsers) or Strict cookies block most cross-site sends.
  • Anti-CSRF tokens (synchroniser or double-submit) for state-changing requests.
  • Check Origin / Sec-Fetch-Site headers on the server; never change state with GET.

Token storage

Tokens in localStorage are readable by any XSS. Session cookies with HttpOnly; Secure; SameSite=Lax cannot be read by JavaScript. A common pattern: a short-lived access token in memory plus a refresh token in an HttpOnly cookie, or a backend-for-frontend (BFF) that keeps tokens on the server.

Example

jsx
import DOMPurify from 'dompurify';

function Comment({ html, website }) {
  const safeHtml = DOMPurify.sanitize(html);                       // strips <script>, onerror=, etc.
  const safeUrl = /^https?:\/\//i.test(website) ? website : '#';    // blocks javascript: URLs
  return (
    <div>
      <div dangerouslySetInnerHTML={{ __html: safeHtml }} />
      <a href={safeUrl} rel="noopener noreferrer" target="_blank">Website</a>
    </div>
  );
}
text
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/
Content-Security-Policy: default-src 'self'; script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'

Follow-up questions interviewers ask

Try answering each one before you open it.

What does CORS protect, and why is it not a security feature for your API?

CORS relaxes the browser's same-origin policy: it lets a page from one origin read responses from another origin if the server allows it (Access-Control-Allow-Origin). It protects users' browsers from other sites reading data with their credentials. It does not stop non-browser clients (curl, scripts) from calling your API, so the API still needs authentication and authorisation. Preflight OPTIONS requests happen for non-simple methods or headers.