Skip to content
GeeksSmith
advanced 8 min read

Frontend Security: XSS, CSRF & Content Security Policy (CSP)

Core web security triad: XSS (executing unauthorized malicious scripts in user's browser), CSRF (tricking an authenticated user into sending forged requests), and CSP (HTTP headers defining trusted script/style/connect origins).

Why it matters in interviews

Security is non-negotiable for Senior & Lead roles. A single XSS flaw can compromise user sessions, steal payment info, and destroy user trust.

Visual & Interactive Explanation

XSS vs CSRF Vulnerability Comparison

Interactive Comparison

XSS (Cross-Site Scripting)

Script Injection in Victim's Browser

Code Injection
VectorInjecting malicious <script>
GoalSteal cookies, keystrokes, DOM data
Primary FixEscaping, DOMPurify, Strict CSP
Strengths
  • React auto-escapes JSX by default
Trade-offs
  • dangerouslySetInnerHTML requires explicit sanitization

CSRF (Cross-Site Request Forgery)

Unauthorized Action on Authenticated Session

Action Forgery
VectorTricking browser to auto-send auth cookies
GoalTransfer funds, change password, delete data
Primary FixSameSite Cookies, Anti-CSRF Token
Strengths
  • SameSite=Lax is default in modern Chrome
Trade-offs
  • GET requests must NEVER mutate state

CSP (Content Security Policy)

Browser Security Header Guardrails

Header Defense
VectorHTTP Header sent by server
GoalWhitelist trusted script & connect domains
Primary Fixscript-src 'self' 'nonce-...'
Strengths
  • Blocks inline injected scripts even if XSS occurs
Trade-offs
  • Requires build-time nonce generation for inline scripts

Code Examples & Implementation

Safe Rich-Text Rendering with DOMPurify & Strict CSP Header
import DOMPurify from 'isomorphic-dompurify';

// 1. Sanitizing user-submitted HTML
export function SafeHtmlViewer({ dirtyHtml }: { dirtyHtml: string }) {
  // DOMPurify strips <script>, onerror handlers, and javascript: URIs
  const cleanHtml = DOMPurify.sanitize(dirtyHtml, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'li', 'code'],
    ALLOWED_ATTR: ['href', 'target', 'rel'],
  });

  return (
    <div
      className="prose text-text"
      dangerouslySetInnerHTML={{ __html: cleanHtml }}
    />
  );
}

// 2. Strict Content Security Policy (in next.config.js / middleware)
const cspHeader = `
  default-src 'self';
  script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
  style-src 'self' 'unsafe-inline';
  img-src 'self' blob: data: https:;
  font-src 'self';
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  block-all-mixed-content;
  upgrade-insecure-requests;
`.replace(/\s{2,}/g, ' ').trim();

Interview-Ready Answers

XSS is malicious script execution in the browser (fixed via input escaping, DOMPurify, and strict CSP). CSRF tricks authenticated browsers into making unauthorized requests (fixed via SameSite=Strict/Lax cookies and anti-CSRF tokens). CSP restricts where scripts and connections can load from.

Official Documentation & Specifications

Follow-up Questions & Deep Dives

Common Mistakes & Anti-Patterns

  • Using `dangerouslySetInnerHTML` with raw user input without DOMPurify
  • Allowing `href={userWebsite}` without checking for `javascript:` pseudoprotocols
  • Allowing state-changing mutations on HTTP GET requests

Real-World Architectural Scenario

A user enters `javascript:alert(document.cookie)` as their profile website link. When another user clicks 'Visit Website', the script runs. How do you prevent this?

Rate Your Readiness

Rate how comfortably you can explain this in an interview to update your global readiness gauge:

Rate your confidence: