Blog>
Snippets

Content Security Policy for Next.js APIs

Elucidate the application of Content Security Policy to Next.js API routes, focusing on securing server-side operations.
import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  // Set Content Security Policy headers
  res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';");
  
  // Your API logic here
  res.status(200).json({ message: 'Secure API route' });
}
This code sets a Content Security Policy (CSP) header for a Next.js API route. The CSP is configured to disallow all sources by default (default-src 'none'), but allows scripts, connections, images, and styles only from the same origin (script-src, connect-src, img-src, style-src all set to 'self'). This is a strict policy that helps to prevent a wide range of attacks including Cross Site Scripting (XSS), data injection, and more. By defining this CSP in your Next.js API routes, you ensure that these routes enforce a strict security policy.