Hmm, the user's query is quite technical and specific, focusing on fine-grained CSP implementation for SPAs/SSR environments with emphasis on nonces/hashes, module scripts, and third-party isolation. They seem to be a developer or security practitioner looking for practical, modern approaches rather than basic CSP concepts.
I should structure this as a comprehensive guide with clear separation of concerns: first establish why traditional CSP fails for modern JS apps, then provide concrete patterns for each of their three areas. Need to emphasize module-script uniqueness since most guides overlook it. The "Dynamic Nonce Generation" pattern must include both server-side (SSR) and client-side (SPA) implementations since they mentioned both architectures.
For third-party isolation, should contrast iframe sandboxing vs. dedicated worker approaches - the latter is less known but valuable for performance. Must warn about strict-dynamic's pitfalls with dynamic imports since that's a common pain point. The summary table will help, but only if it contrasts SPA vs SSR approaches explicitly.
Should avoid over-explaining CSP basics - they clearly know the fundamentals. Focus on actionable code snippets with security annotations. The worker-based third-party isolation example needs to show real postMessage patterns since that's where implementations often break.
Excellent question. You're touching on the cutting edge of deploying robust Content Security Policy (CSP) for modern JavaScript applications (SPA/SSR) where the old "static hash/nonce for every script" model breaks down.
Here’s a deep dive into fine-grained CSP strategies tailored for your three pillars.
Core Philosophy: From "Allowlist" to "Trust Boundary"
Traditional CSP (script-src 'self') is too blunt. For SPAs/SSR, we shift to:
Nonces/Hashes for your code. (You control it, you sign it.)
Strict isolation for third-party code. (You don't control it, quarantine it.)
Explicit permission for dynamic imports. (The import() function is the SPA's heartbeat.)
1. Nonces & Hashes: The "Your Code" Vault
The Problem: In an SPA, your main bundle (main.js) is one file, but it dynamically imports many chunks (chunk-abc123.js). You cannot pre-compute hashes for all possible chunks at build time for a static CSP header.
Solutions:
A. For SSR (Server-Side Rendered) Apps (Next.js, Remix, Nuxt)
Pattern:Dynamic Nonce Injection.
How it works:
Server generates a cryptographically random nonce (req.cspNonce = crypto.randomBytes(16).toString('hex')) per request.
This nonce is passed to your templating engine and injected into:
The CSP header: Content-Security-Policy: script-src 'nonce-${req.cspNonce}' ...
Every <script> tag for your own code: <script nonce="${req.cspNonce}">.
For dynamically imported modules (<script type="module">), the nonce must also be on the module script tag itself.
Key Insight: Any script tag without the correct nonce is blocked, even if it's a dynamically injected module script. You must ensure your client-side dynamic import mechanism (import()) creates <script type="module" nonce="..."> elements. Frameworks like Next.js handle this internally when you set cspNonce in your config.
B. For SPAs (Client-Side Rendered) & Build-Time Hashes
Pattern:Subresource Integrity (SRI) for Bundles + Nonce for Inline.
How it works:
Static Files (vendor.js, main.js, chunks): At build time, generate SRI hashes (sha384-...) for every output file. CSP header: script-src 'sha384-...' 'sha384-...' .... The browser verifies the file hasn't been tampered with.
Inline Scripts (bootstrapping, config): Use a nonce. CSP header must include 'nonce-...' and the inline script must have that nonce.
Dynamic Imports: This is the hard part. You cannot use SRI for truly dynamic chunks (e.g., import(./chunks/${id}.js`)). You must fall back to a nonce strategy.
Solution: Have your build output a small, nonce-validated bootstrap script (import-bootstrap.js). This script, loaded with a nonce, is responsible for creating all subsequent dynamic <script type="module"> tags and must copy the original nonce onto them.
Example Bootstrap Logic (pseudo):
javascript
// This file is included via <script nonce="...">
const originalNonce = document.currentScript.getAttribute('nonce');
async function dynamicImport(url) {
const script = document.createElement('script');
script.type = 'module';
script.src = url;
script.nonce = originalNonce; // CRITICAL: Pass the nonce!
document.head.append(script);
await new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = reject;
});
// ... cleanup?
}
// Your app uses this dynamicImport() instead of native import()
2. Module Scripts: The type="module" Quirk
They are separate from classic scripts. CSP treats them differently. A nonce- or sha- on a classic <script> does not apply to a <script type="module">.
You must explicitly allow them:script-src ... 'nonce-...' allows classic scripts with that nonce. You need script-src ... 'nonce-...'AND for modules, either:
The module script tag itself has the valid nonce.
The module's own dependencies (which are fetched as classic scripts by the browser) must be allowed by the policy. This is the trap. A module import triggers a classic script fetch for each dependency. Those fetches need to be allowed by script-src.
Strategy: Your CSP script-src directive must cover both:
The nonce-/hash for the initial module script tag.
The source ('self' or specific domains) for all the static module dependencies that will be fetched as classic scripts. For dynamic chunks, you must rely on the nonce-copying bootstrap logic above.
3. Third-Party Isolation: The "Don't Trust Anyone" Mandate
This is where you prevent a compromised analytics/ad network from running arbitrary code in your origin's context.
A. The Gold Standard: sandbox with allow-scripts on iframes
How: Load all third-party scripts only inside a dedicated, same-origin iframe.
The iframe has its own isolated DOM, JS global, and CSP.
sandbox removes its ability to affect the parent (no top access, no cookie access unless allow-same-origin - use cautiously).
You communicate via window.postMessage().
Use for: Ads, social widgets, complex third-party widgets.
B. The Modern Alternative: Dedicated Workers (for "headless" third-parties)
How: Load the third-party script as a module inside a Dedicated Worker.
javascript
// main-thread.js (nonce-protected)
const worker = new Worker('/third-party-worker.js', { type: 'module' });
worker.postMessage({ event: 'init', data: ... });
worker.onmessage = (e) => { /* handle data */ };
// third-party-worker.js (served from your origin)
// This file's CSP is controlled by your main app's CSP for Worker scripts.
importScripts('https://untrusted-analytics.com/tracker.js'); // BLOCKED if not in worker CSP!
// The worker's global scope is isolated from the DOM.
CSP for Worker: You need a separate CSP header for the worker script (via server config for /third-party-worker.js). It can be more permissive for network sources (connect-src) but neverscript-src 'unsafe-inline' or 'unsafe-eval'.
Why it works: The worker runs in a separate thread with no DOM access. importScripts is its only way to get code. It's perfect for pure computation/data-fetching third-party libraries.
Use for: Analytics SDKs, data processing libraries, crypto libraries.
C. The Last Resort: strict-dynamic with Careful Bootstrapping
What:script-src 'nonce-...' 'strict-dynamic' says: "Trust whatever scripts are directly or indirectly loaded by a script with a valid nonce."
The Danger: A single XSS that injects a script with the nonce (e.g., via a DOM-based XSS that reads the nonce from document.currentScript) can load any other script. It reduces the power of the nonce to a single point of failure.
Use only if: You have 100% confidence your nonce is never exposed to the DOM (extremely difficult). Generally, avoid strict-dynamic for SPAs where you need dynamic imports. Use the nonce-copying bootstrap method instead.
Implementation Summary & Decision Tree
Scenario
Recommended CSP Pattern
Key Directive
Third-Party Strategy
SSR Framework (Next.js/Remix)
Dynamic Nonce per request
script-src 'nonce-${nonce}'
Use iframe sandbox for widgets. Use Worker for headless libs.
SPA with Build (Vite/Webpack)
SRI for static files + nonce-copying bootstrap for dynamic imports
script-src 'sha384-...' 'nonce-...'
Same as above.
Pure Static Site
SRI for all scripts (no dynamic imports)
script-src 'sha384-...'
Iframe sandbox only.
Final Checklist:
Nonce is truly random per request/load.
Nonce is injected into every<script> tag you create, including dynamic module scripts.
CSP header script-src includes the mechanism for all your scripts (nonce/hash/SRI).
script-src does NOT contain 'unsafe-inline' or 'unsafe-eval'.
Third-party code is isolated:
Path A (iframe): Loaded only in a sandboxed iframe with its own CSP.
Path B (Worker): Loaded only in a dedicated worker via importScripts().
Test thoroughly: Use your browser's DevTools > Security tab and Network tab (filter "csp-report") to see violations. Start with Content-Security-Policy-Report-Only to debug.
By implementing this fine-grained separation—nonce/hashes for your immutable code, and strict isolation for all third-party code—you achieve a formidable security posture against both XSS and supply-chain attacks in modern JavaScript applications.