Fine-Grained CSP for SPA/SSR Apps
Content Security Policy (CSP) is crucial for SPAs (e.g., React/Vite) and SSR apps (e.g., Next.js/Nuxt) to mitigate XSS by restricting resource loading. Fine-grained CSP avoids 'unsafe-inline' and 'unsafe-eval' by using nonces, hashes, module scripts, and isolation headers like COOP/COEP. This enables strict policies while supporting dynamic JS/CSS.
Key challenges in SPA/SSR:
- Inline scripts/styles: Bootstrapping (e.g., hydration in SSR).
- Dynamic loading: Bundlers like Vite/Webpack inject code.
- Third-parties: Analytics/CDNs need isolation to prevent Spectre-like attacks.
1. Nonces (Dynamic, Per-Request Tokens)
- Generate a random nonce server-side (crypto.randomUUID() or base64url(CSPRNG(16))).
- Embed in
<script nonce="abc123"> or <style nonce="abc123">.
- CSP:
'nonce-abc123'.
- SSR: Pass nonce via props/context (e.g., Next.js
headers()).
- SPA: Use meta tag or service worker to inject nonce (trickier; prefer hashes for static builds).
Pros: Works for inline + eval (if needed).
Cons: Must regenerate per request; no caching of inline content.
2. Hashes (Static Content Digests)
- SHA-256/384/512 hash of exact inline content:
sha256-<base64-hash>.
- Tools:
openssl dgst -sha256 -binary script.js | openssl base64 -A.
- CSP:
'sha256-abc123...'.
- SPA/SSR: Ideal for build-time inlines (e.g., Vite's index.html). Re-hash on content changes.
- Multiple hashes: Space-separated (e.g., for multiple snippets).
Pros: Cacheable, no runtime overhead.
Cons: Breaks if content changes (use in CI/CD).
3. Module Scripts (ES Modules Bypass Inline Restrictions)
Vite Example (SPA/SSR hybrid):
// vite.config.js
export default {
build: { target: 'esnext' }, // ES modules
};
4. Third-Party Isolation (COOP/COEP/CORP)
- Cross-Origin Opener Policy (COOP):
Cross-Origin-Opener-Policy: same-origin isolates third-party windows/popups.
- Cross-Origin Embedder Policy (COEP):
Cross-Origin-Embedder-Policy: require-corp blocks non-opt-in cross-origin resources (enables SharedArrayBuffer).
- Cross-Origin Resource Policy (CORP):
Cross-Origin-Resource-Policy: same-site on third-party fetches.
- Full stack: Enables
crossOriginIsolated for high-perf features (e.g., threads).
CSP Integration: Use frame-ancestors 'self' + above for iframes.
Sample Fine-Grained CSP Header
For a Vite/Next.js app with modules + nonces/hashes:
Content-Security-Policy:
default-src 'self';
base-uri 'self';
block-all-mixed-content;
child-src 'self';
connect-src 'self' https://api.example.com wss://ws.example.com;
font-src 'self' data: https://fonts.gstatic.com;
form-action 'self';
frame-ancestors 'none'; /* No iframes */
frame-src 'none';
img-src 'self' data: blob: https:; /* Avatars/CDNs */
manifest-src 'self';
media-src 'self';
object-src 'none';
prefetch-src 'self';
script-src
'self'
'nonce-{NONCE}' /* Inline bootstrap */
'sha256-{HASH1}' 'sha256-{HASH2}' /* Specific inlines */
https://cdn.example.com /* Trusted CDNs */
'wasm-unsafe-eval'; /* WebAssembly */
script-src-attr 'none';
style-src
'self'
'nonce-{NONCE}'
'sha256-{STYLEHASH}'
https://fonts.googleapis.com;
style-src-attr 'none';
style-src-elem 'self' https://fonts.googleapis.com;
worker-src 'self' blob:;
upgrade-insecure-requests;
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Resource-Policy: same-site
Permissions-Policy: interest-cohort=()
Referrer-Policy: strict-origin-when-cross-origin
Implementation Tips
| Scenario | Nonce/Hash | Modules | Isolation |
|---|
| Pure SPA (Vite) | Build-time hashes | Yes (type="module") | COOP/COEP on index.html |
| SSR (Next.js) | Server-gen nonce | Yes (dynamic imports) | Per-page headers |
| Third-party | Hashes only | Strict script-src | CORP on CDNs |
| Testing | Report-Only mode: Content-Security-Policy-Report-Only | Chrome DevTools CSP tab | crossOriginIsolated check in console |
Tools & Validation
- Generate Hashes: CSP Hash Generator or
curl -H "Content-Security-Policy-Report-Only: ...".
- Audit:
npx @cspbuilder/builder, securityheaders.com.
- Pitfalls: Polyfills break modules; eval() needs
'unsafe-eval' (avoid). Service workers: worker-src 'self'.
This setup blocks 99% of XSS while keeping perf high. Need code for a specific framework? Ask! 🔍