0 day streak
javascript / expert
Snippet

Strict Content Security Policy (CSP) Implementation with Nonces

Nonces (number used once) allow you to safely execute inline scripts while maintaining a strict CSP that blocks unauthorized scripts. This is a critical security pattern in Next.js applications to prevent Cross-Site Scripting (XSS) attacks.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// app/layout.tsx
import { headers } from 'next/headers';
import Script from 'next/script';
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get('x-nonce') || '';
return (
<html lang="en">
<body>
{children}
<Script
id="secure-analytics"
nonce={nonce}
strategy="afterInteractive"
dangerouslySetInnerHTML={{ __html: `window.initAnalytics('${nonce}')` }}
/>
</body>
</html>
);
}
nextjs
Breakdown
1
headers().get('x-nonce')
Retrieving the unique nonce generated in middleware to authorize inline script execution.
2
nonce={nonce}
Passing the cryptographic token to the Next.js Script component to satisfy strict CSP headers.