javascript / expert
Snippet
Secure Inline Scripts with CSP Nonces
To prevent Cross-Site Scripting (XSS), a Content Security Policy (CSP) can disallow all inline scripts unless they contain a cryptographic 'nonce'. In Next.js, you generate a unique nonce per request in middleware and pass it to your components to authorize specific trusted scripts.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// middleware.tsimport { NextRequest, NextResponse } from 'next/server';export function middleware(request: NextRequest) {const nonce = Buffer.from(crypto.randomUUID()).toString('base64');const cspHeader = `script-src 'self' 'nonce-${nonce}'`;const response = NextResponse.next();response.headers.set('Content-Security-Policy', cspHeader);response.headers.set('x-nonce', nonce);return response;}// layout.tsxexport default function Layout({ children }) {const nonce = headers().get('x-nonce');return (<html><body>{children}<script nonce={nonce} dangerouslySetInnerHTML={{ __html: `console.log('Safe!')` }} /></body></html>);}
nextjs
Breakdown
1
nonce = crypto.randomUUID()
Generates a cryptographically strong unique identifier for the current request.
2
script-src 'nonce-${nonce}'
Tells the browser to only execute inline scripts that provide this exact matching nonce.