Blog>
Snippets

Handling External Resources with Content Security Policy

Provide an example of managing external resources such as fonts or frames in a Content Security Policy with Next.js 14.
import { ContentSecurityPolicy } from 'next/security';

export const config = {
  runtime: 'experimental-edge',
};

export default async function handler(req) {
  const csp = new ContentSecurityPolicy();

  // Add CSP rules for font sources
  csp.fontSrc.add('https://fonts.googleapis.com').add('https://fonts.gstatic.com');

  // Add CSP rules for frame sources
  csp.frameSrc.add('https://www.youtube.com').add('https://player.vimeo.com');

  // Other CSP directives can be added here as needed
  //csp.scriptSrc.add('https://your-trusted-script-source.com');

  const headers = new Headers({
    'Content-Security-Policy': csp.toString(),
  });

  // Set the CSP headers for the response
  return new Response('This is the body', {
    headers,
  });
}
This code snippet is meant to be used in a Next.js 14 application. It imports the ContentSecurityPolicy helper from 'next/security' and uses it to create a new CSP instance. The fontSrc.add() method is used to add trusted sources for fonts, defining where fonts can be loaded from. Similarly, the frameSrc.add() method is used to define trusted sources for frames. Other CSP directives can be added in a similar manner. The CSP rules are serialized into a string and set as the 'Content-Security-Policy' header in the response.