Blog>
Snippets

Implementing custom headers in Next.js Edge functions

Demonstrate how to set custom response headers in an Edge function, such as setting Content-Security-Policy or CORS headers.
import { NextResponse } from 'next/server';

export function middleware(request) {
  // Create a response by calling NextResponse.next() to continue the processing
  const response = NextResponse.next();

  // Set the Content-Security-Policy header for security
  response.headers.set('Content-Security-Policy', "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';");

  // Set the CORS (Cross-Origin Resource Sharing) headers
  response.headers.set('Access-Control-Allow-Origin', '*');
  response.headers.set('Access-Control-Allow-Methods', 'GET, POST');
  response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');

  return response;
}

export const config = {
  matcher: '/some-path*', // Specify the path to apply this middleware
};
This snippet defines a Next.js Edge middleware function that adds custom headers to the response. It sets a Content-Security-Policy header for enhanced security and CORS headers to allow cross-origin requests. 'NextResponse.next()' continues the request without altering it, and the 'response.headers.set()' method is used to add or modify headers on the response.