javascript / expert
Snippet
Content Security Policy Nonce Ingestion via Next.js Headers Middleware
This expert-level snippet generates a cryptographically secure random 16-byte nonce within Next.js Middleware. It dynamically constructs a strict Content Security Policy (CSP) header and forwards the nonce to both upstream React Server Components via request headers and downstream HTTP clients via response headers, throwing a wrapped error if entropy generation fails.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { NextResponse } from 'next/server';export function middleware(request) {try {const nonce = Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64');const cspHeader = `default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic';`;const requestHeaders = new Headers(request.headers);requestHeaders.set('x-nonce', nonce);requestHeaders.set('Content-Security-Policy', cspHeader);const response = NextResponse.next({ request: { headers: requestHeaders } });response.headers.set('Content-Security-Policy', cspHeader);return response;} catch (error) {throw new Error(`CSP Nonce Generation Failed: ${error.message}`);}}
nextjs
Breakdown
1
const nonce = Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64');
Generates a cryptographically strong 16-byte random buffer using the Web Crypto API and encodes it to Base64.
2
const requestHeaders = new Headers(request.headers);
Clones incoming request headers to allow mutation and header injection for React Server Components.
3
response.headers.set('Content-Security-Policy', cspHeader);
Applies the final strict CSP security directive directly to the outgoing HTTP response headers.