Enhancing Security with Strict-Dynamic in Next.js 14
Showcase how to further tighten security by adding the 'strict-dynamic' directive in a Content Security Policy, allowing trusted scripts to load additional scripts in Next.js 14.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Add Content-Security-Policy header with strict-dynamic directive
const csp = `default-src 'self'; script-src 'strict-dynamic' 'nonce-RANDOM' 'unsafe-inline' https:; object-src 'none';`;
response.headers.set('Content-Security-Policy', csp.replace('RANDOM', generateNonce()));
return response;
}
// Function to generate a strong nonce value
function generateNonce() {
return crypto
.randomBytes(16)
.toString('base64')
.replace(/[^a-zA-Z0-9]/g, ''); // Remove non-alphanumeric characters
}
This Next.js middleware function sets a Content Security Policy header with a 'strict-dynamic' directive, allowing scripts to load additional scripts if they are approved by a nonce or hash. A random nonce is generated for each request using the 'generateNonce' function.