Chapter 66: Content Security Policy (CSP)

Production CSP Recipes for SPAs, Static Sites & APIs

**Part 14: Security & Best Practices** — Chapter 66: Content Security Policy (CSP)

LEARNING OBJECTIVES
  • Deploy drop-in production CSP recipes for Single Page Applications (Next.js, Vite, React).
  • Configure strict static site CSPs for GitHub Pages / Cloudflare Pages.
  • Protect against clickjacking with frame-ancestors 'none'.
  • Prevent HTTPS downgrade attacks with upgrade-insecure-requests.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

Master Production CSP Recipe (Strict Nonce Architecture)

Content-Security-Policy:
  default-src 'self';
  script-src 'nonce-{SERVER_GENERATED_NONCE}' 'strict-dynamic' https: 'unsafe-inline';
  style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
  font-src 'self' https://fonts.gstatic.com;
  img-src 'self' data: https: blob:;
  connect-src 'self' https://api.yourdomain.com wss://ws.yourdomain.com;
  object-src 'none';
  base-uri 'self';
  form-action 'self';
  frame-ancestors 'none';
  upgrade-insecure-requests;

📌 Key Takeaways

  • frame-ancestors 'none' completely eliminates Clickjacking vulnerabilities across modern browsers.
  • upgrade-insecure-requests automatically rewrites all legacy HTTP asset requests to HTTPS before network dispatch.
  • --

❓ Knowledge Check

1. Which of the following is correct?

2. Which of the following is correct?

🏋️ Study Exercise

Task: Review the http example above. Identify the key directives and their purpose, then try writing your own version from memory.

Content-Security-Policy: default-src 'self'; script-src 'nonce-{SERVER_GENERATED_NONCE}' 'strict-dynamic' https: 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https: blob:; connect-src 'self' https://api.yourdomain.com wss://ws.yourdomain.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests;