Resolving Content Security Policy Inline Script Violations in Next.js App Router
Resolve Content Security Policy (CSP) inline script violations in Next.js App Router using cryptographic nonces in Edge Middleware. Protect against XSS without breaking hydration.
Displayed below main page header or above the tool container. • Zero CLS Container
Automate & Test This in Our Free Tool
Eliminate syntax errors and test live URLs client-side using our dedicated Content Security Policy (CSP) & Header Builder.
The Technical Problem & Root Cause
Next.js injects framework hydration scripts inline. A strict script-src 'self' CSP policy blocks these scripts, causing hydration failures and blank screens.
Refused to execute inline script because it violates the following Content Security Policy directive: script-src 'self'
Production-Grade Solution & Code Snippet
Copy and paste this verified configuration directly into your project:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data: https:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`.replace(/\s{2,}/g, ' ').trim();
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;
}
export const config = {
matcher: [
{
source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
};Step-by-Step Implementation Walkthrough
11. Generate Cryptographic Nonce in Edge Middleware
Generate a cryptographic random nonce per request inside Next.js edge middleware.
22. Pass Nonce via Request Headers to Root Layout
Pass the nonce down via request headers to layout.tsx so Server Components can read it.
33. Attach Nonce to Third-Party Next.js Script Tags
Attach the nonce attribute to Google Tag Manager or third-party Next.js Script tags to permit runtime execution.
Separates the interactive tool output from the deep technical guide. • Zero CLS Container
- Caching static HTML pages with stale nonce values on a CDN or Vercel edge edge-cache.
- Applying middleware CSP headers to static assets (_next/static), breaking CDN caching efficiency.
- Forgetting 'strict-dynamic', which blocks dynamically loaded third-party libraries spawned by trusted inline scripts.
- Using 'unsafe-inline' alongside nonces without understanding that modern CSP3 browsers ignore 'unsafe-inline' when a nonce is present.
Frequently Asked Questions
What is the difference between CSP nonces and CSP hashes?▼
A nonce (number used once) is a unique cryptographically generated token generated per request, allowing dynamic inline scripts. A hash (e.g., sha256-...) is static and represents the exact cryptographic checksum of an unchanging script body. Nonces are required when script contents change dynamically.
Can I use CSP nonces with static export (output: 'export') in Next.js?▼
No. Static HTML export generates pre-rendered HTML files at build time without a server runtime to inject per-request nonces. For static exports, use sha256 script hashes or configure CSP headers in next.config.mjs or hosting headers (Vercel vercel.json, Netlify _headers).
Why is 'strict-dynamic' recommended in modern CSP policies?▼
'strict-dynamic' instructs modern browsers to automatically trust any script created and executed by a root script that already possesses a valid nonce. This eliminates the need to maintain an exhaustive, fragile whitelist of third-party domains for analytics, chat widgets, and tag managers.
Related Tools & Next Workflow Steps
Complementary utilities to streamline your SEO audit, indexing, and content strategy.
Security Headers Meta Generator
Generate production-grade Content-Security-Policy (CSP), Strict-Transport-Security, and Referrer-Policy head tags and headers.
Resource Hint & Preconnect Generator
Generate and validate preload, preconnect, dns-prefetch, and prefetch tags for Next.js, HTML, and HTTP headers to optimize Core Web Vitals.
Meta Viewport Generator
Generate responsive HTML5 meta viewport tags and Next.js viewport exports with viewport-fit cover and device-width scaling.
Robots.txt Generator & Validator
Generate, test, and validate standard-compliant robots.txt files with live syntax checking, multi-user-agent rules, and sitemap directives.
Displayed below main page header or above the tool container. • Zero CLS Container