Content Security Policy
Learn how to set a Content Security Policy (CSP) for your Next.js application.
Content Security Policy (CSP) is important to guard your Next.js application against various security threats such as cross-site scripting (XSS), clickjacking, and other code injection attacks.
By using CSP, developers can specify which origins are permissible for content sources, scripts, stylesheets, images, fonts, objects, media (audio, video), iframes, and more.
Examples
Nonces
A nonce is a unique, random string of characters created for a one-time use. It is used in conjunction with CSP to selectively allow certain inline scripts or styles to execute, bypassing strict CSP directives.
Why use a nonce?
Even though CSPs are designed to block malicious scripts, there are legitimate scenarios where inline scripts are necessary. In such cases, nonces offer a way to allow these scripts to execute if they have the correct nonce.
Adding a nonce with Middleware
Middleware enables you to add headers and generate nonces before the page renders.
Every time a page is viewed, a fresh nonce should be generated. This means that you must use dynamic rendering to add nonces.
For example:
By default, Middleware runs on all requests. You can filter Middleware to run on specific paths using a matcher
.
We recommend ignoring matching prefetches (from next/link
) and static assets that don't need the CSP header.
Reading the nonce
You can now read the nonce from a Server Component using headers
:
Without Nonces
For applications that do not require nonces, you can set the CSP header directly in your next.config.js
file:
Version History
We recommend using v13.4.20+
of Next.js to properly handle and apply nonces.