Blog>
Snippets

Combining Content Security Policy with Other Next.js Security Headers

Demonstrate how to combine Content Security Policy with other security-related headers like X-Frame-Options and X-Content-Type-Options in Next.js 14.
import { NextResponse } from 'next/server';

export function middleware(request) {
  const response = NextResponse.next();
  
  // Define the Content Security Policy
  const csp = `default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none';`;
  
  // Apply the Content Security Policy
  response.headers.set('Content-Security-Policy', csp);
  
  // Prevent the document from being displayed in an iframe (clickjacking protection)
  response.headers.set('X-Frame-Options', 'DENY');
  
  // Prevent MIME types sniffing (security vulnerability)
  response.headers.set('X-Content-Type-Options', 'nosniff');
  
  // Return the response to the client
  return response;
}
This code snippet is to be used in the 'middleware.js' file for a Next.js 14 project. It includes a middleware function that intercepts requests and applies a set of security-related headers. The Content Security Policy (CSP) is defined as a strict policy that only allows default and script sources from the same origin and prevents object and base-uri directives entirely. Additionally, the code includes the X-Frame-Options header set to 'DENY' to protect against clickjacking attacks by preventing the site from being embedded in iframes on other sites. The X-Content-Type-Options header is set to 'nosniff' to block MIME type sniffing that could lead to security vulnerabilities.