Skip to the page

XSS and injection in the browser · senior

Content Security Policy: strict CSP with nonces, hashes and strict-dynamic

A strict CSP allows only scripts that carry a per-response nonce or a known hash, uses 'strict-dynamic' so those trusted scripts can load others, blocks plugins and base-tag tricks, and is rolled out in report-only mode first.

The notes

What you must know

  • Recommended strict CSP: script-src 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'none'. Use hashes ('sha256-...') instead of nonces for static pages that are cached.
  • Nonce: a new random value (at least 128 bits, base64) for EVERY response, added to each <script nonce=...>. A reused or predictable nonce gives no protection.
  • 'strict-dynamic': scripts loaded by a nonced script are trusted too, and host allow-lists are ignored. This makes third-party loaders work.
  • Host allow-lists (script-src cdn.example.com) are often bypassable (JSONP endpoints, old library versions on the same CDN). Prefer nonce/hash based policies.
  • Fallbacks for very old browsers: add https: and 'unsafe-inline'; browsers that support nonces/strict-dynamic ignore them.
  • Rollout: Content-Security-Policy-Report-Only with a reporting endpoint, fix violations, then enforce. frame-ancestors (clickjacking) and require-trusted-types-for 'script' (DOM XSS) live in CSP too.
  • frame-ancestors, report-uri and sandbox don't work in a <meta> CSP; send CSP as a header.

The red pen

Common traps: mistake → fix

  • Mistake: "script-src 'self' 'unsafe-inline' means we have CSP"

    Fix: unsafe-inline allows injected inline scripts, so it gives almost no XSS protection.

  • Mistake: "Use a fixed nonce in the HTML template"

    Fix: a static nonce can be copied by the attacker; generate it per response.

  • Mistake: "CSP replaces output encoding"

    Fix: CSP is defence in depth; you still must not create XSS bugs.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is CSP and what attacks does it reduce?
  2. Why are nonce-based policies better than host allow-lists? What does strict-dynamic do?
  3. How do you roll out CSP on an app with many third-party scripts without breaking production?
  4. How do nonces work with SSR, streaming and CDN caching in Next.js?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview