The user wants a "Fine-grained CSP for SPA/SSR" focusing on "nonces/hashes, module scripts, third-party isolation."
1. Deconstruct the Request:
Context: Single Page Applications (SPA) and Server-Side Rendered (SSR) apps. These are distinct but often overlap in modern frameworks (Next.js, Nuxt, Remix, SvelteKit).
Fine-grained: Not just a basic policy, but strict, minimized privileges.
Nonces/Hashes: The modern way to allow inline scripts/styles (replacing unsafe-inline).
Module Scripts: Handling ES6 modules (type="module"), which behave slightly differently in CSP (strict-dynamic).
Third-party Isolation: How to safely include analytics, ads, widgets, etc., without compromising the whole app.
2. Identify the Challenges:
SPAs: Often rely heavily on client-side logic. Build tools might inject inline scripts. Frameworks might use eval or Function (though less common now).
SSR: The server generates the HTML, so generating nonces is easier. However, hydration scripts and state serialization (JSON blobs in script tags) are pain points.
Module Scripts:script-src-elem vs script-src. The concept of "loose" vs "strict" dynamic.
Third-Party: Usually the weakest link. Needs sandboxing (iframes) or strict specific domains.
3. Structure the Guide:
A technical guide should be structured logically:
Use case: Static inline scripts (e.g., a specific analytics snippet) that don't change often.
Drawback: Build process complexity. If the script changes, hash breaks.
Nuance: Module Scripts (type="module")
Module scripts behave differently. They automatically bypass some restrictions if the root is trusted.
strict-dynamic is key here. If I trust the entry point (via nonce), the imports it fetches are automatically trusted? Correction: Actually, module scripts often don't need nonces on the imported files themselves if the root is nonce'd, but browsers handle this well with 'strict-dynamic'.
Nuance: JSON Payloads (Hydration)
Problem:window.__INITIAL_STATE__ = {...} inside a script tag.
Solution: This is an inline script. Needs a nonce. Or move to JSON script type="application/json" and parse it. The latter is safer (prevents DOM Clobbering/XSS if the nonce is leaked/brute-forced, though unlikely).
Strategy 3: Third-Party Isolation
The Problem:*.google-analytics.com allows any script from there.
The Solution (Heavy): Sandboxed iframes (sandbox attribute).
The Solution (Medium):strict-dynamic. If a third-party script creates new scripts dynamically, strict-dynamic covers it if the root script had a nonce. This is better than unsafe-inline.
Specific Directives:connect-src (for fetch/XHR), (pixels), (iframes).
5. Refining the Advice (Self-Correction/Edge Cases):
Issue:'unsafe-eval'.
Context: Some legacy libs or template engines need eval.
Fix: Avoid if possible. If necessary, isolate that specific part to a sandboxed iframe or use wasm-unsafe-eval if applicable.
Issue:style-src.
Context: CSS-in-JS.
Fix: Nonces on <style> tags or 'unsafe-hashes' for inline styles (e.g., style="color: red").
6. Final Polish:
Organize into clear headings.
Use code blocks for examples.
Keep the tone professional and technical.
Highlight "Strict-Dynamic" as it's the MVP of modern CSP.
7. (Mental Outline for Output):
Architecture Overview: SSR vs Static SPA nonce generation.
The Gold Standard: strict-dynamic + Nonces.
Implementation Details:
SSR (Server middleware).
SPA (Static hosting via Function/Worker).
Build pipeline (Hash generation).
Module Scripts & Dependencies: Handling the import tree.
Third-Party Strategy: The "Trust Tree" vs. Sandboxing.
Style Source: Handling CSS-in-JS.
Reporting.
Let's write the response based on this structure. Ensure to mention that unsafe-inline is effectively ignored by modern browsers when a nonce/hash is present, which is a common confusion point.
(Self-Correction during drafting): Make sure to address the "JSON injection" vector. Putting JSON data into a <script> tag is risky if not done carefully. Recommend JSON script tags.
Let's produce the output.
Implementing a fine-grained Content Security Policy (CSP) for modern Single Page Applications (SPAs) and Server-Side Rendered (SSR) apps requires moving away from legacy whitelist approaches (which are susceptible to bypasses) toward a Nonce/Hash-based strategy with Strict-Dynamic.
Here is the architectural breakdown for implementing robust CSP focusing on nonces, module scripts, and third-party isolation.
1. The Core Strategy: strict-dynamic & Nonces
Do not use script-src 'self' https://trusted-cdn.com. This is "coarse-grained" and insecure if the CDN is compromised.
Instead, use a Trust Chain:
The Server generates a unique random string (Nonce) for every request.
The Server injects this Nonce into the HTTP Header and the HTML <head>.
JavaScript files loaded by a trusted script are automatically trusted (via strict-dynamic).
'unsafe-inline': Required for backward compatibility. Modern browsers ignore this directive if a nonce or hash is present; older browsers use it as a fallback.
https:: Fallback for older browsers (ignoring strict-dynamic). Modern browsers ignore this.
2. SPA vs. SSR: Implementation Patterns
A. Server-Side Rendered (SSR) Frameworks (Next.js, Remix, Nuxt)
SSR is the easiest environment for CSP because the server constructs the HTML dynamically.
Middleware/Server Hook: Generate a cryptographically secure random string (Base64) on every HTTP request.
Injection:
Append to the CSP header.
Pass to the template context.
Root Scripts:
html
<!-- Your main entry bundle -->
<script src="/bundle.js" nonce="{RANDOM}"></script>
B. Client-Side Rendered (SPAs) (React/Vue/Angular on S3/CDN)
Static SPAs are harder because the index.html is static. You cannot embed a server-generated nonce into a static file effectively.
Solution: You must serve the index.html via a lightweight edge function (Cloudflare Workers, AWS Lambda@Edge, Vercel Edge Middleware).
Intercept the request for index.html.
Generate the Nonce.
Inject the Nonce into the CSP header.
Parse the HTML body and inject the nonce="..." attribute into your script tags (or use a placeholder replacement like __NONCE__).
3. Handling Module Scripts (type="module")
ES Modules introduce specific behaviors regarding CSP.
The Import Tree
If your entry script <script type="module" src="app.js" nonce="..."> is trusted, you do not need to nonce its dependencies.
app.js imports utils.js.
utils.js imports library.js.
Because app.js has a valid nonce, utils.js and library.js are automatically trusted by strict-dynamic.
Caveat: External CDNs
If you import a module from a CDN (e.g., import React from 'https://esm.sh/react'), the browser fetches it.
Modern Browsers: The imported module is trusted because the referrer (your nonced script) is trusted.
Legacy Browsers (Safari < 15.4): May require the https: fallback in the header to load these external imports.
Inline Module Scripts
Avoid this pattern:
html
<script type="module" nonce="...">
import React from 'react';
// code here
</script>
While secure with a nonce, this forces the browser to parse HTML strings as JS. It is generally better to point to a file source for caching and parsing efficiency.
For scripts you do not trust (e.g., Ad units, chat widgets), load them in a sandboxed iframe, ideally on a separate subdomain (e.g., sandbox.yoursite.com).
Parent CSP:
http
frame-src https://sandbox.yoursite.com;
Iframe Sandbox:
Use the sandbox attribute to strip permissions.
<html>
<head>
<!-- Trusted Root Script -->
<script nonce="{RAND}" src="/static/js/main.js"></script>
<!-- Third Party Script (Needs Nonce to bootstrap) -->
<script nonce="{RAND}" async src="https://www.googletagmanager.com/gtag/js?id=GA_ID"></script>
<!-- Inline Initialization (Needs Nonce) -->
<script nonce="{RAND}">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_ID');
</script>
</head>
<body>...</body>
</html>
Key Takeaways
unsafe-inline is ignored by modern browsers if a nonce is present; keep it in the header strictly for legacy browser support.
strict-dynamic is your best friend; it removes the need to whitelist every subdomain.
SSR is superior for CSP; it allows per-request nonces without complex edge-function workarounds.
Isolate third parties in frames whenever possible; if not, ensure they support strict-dynamic loading.
img-src
frame-src
The "Strict" Policy Template:
Construct a header string.
default-src 'self'
script-src 'strict-dynamic' 'nonce-...' 'unsafe-inline' http: https: (Note: 'unsafe-inline' is ignored by modern browsers if nonce is present, but kept for fallback; http: is ignored if strict-dynamic is supported). Self-correction: This is the "backward compatibility" pattern. For a "fine-grained" modern guide, we can focus on the modern pattern but acknowledge the fallback.
Framework Implementation (e.g., Next.js)
Next.js has a CSP header config.
It has a Script component (next/script) that handles nonce.