--- title: How to set a Content Security Policy (CSP) for your Next.js application nav_title: Content Security Policy description: Learn how to set a Content Security Policy (CSP) for your Next.js application. related: links: - app/api-reference/file-conventions/middleware - app/api-reference/functions/headers --- {/* The content of this doc is shared between the app and pages router. You can use the `Content` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} [Content Security Policy (CSP)](https://developer.mozilla.org/docs/Web/HTTP/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 - [Strict CSP](https://github.com/vercel/next.js/tree/canary/examples/with-strict-csp)
## Nonces A [nonce](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/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](/docs/app/api-reference/file-conventions/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](/docs/app/getting-started/partial-prerendering#dynamic-rendering) to add nonces**. For example: ```ts filename="middleware.ts" switcher import { NextRequest, NextResponse } from 'next/server' export function middleware(request: NextRequest) { const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const cspHeader = ` default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; style-src 'self' 'nonce-${nonce}'; img-src 'self' blob: data:; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; ` // Replace newline characters and spaces const contentSecurityPolicyHeaderValue = cspHeader .replace(/\s{2,}/g, ' ') .trim() const requestHeaders = new Headers(request.headers) requestHeaders.set('x-nonce', nonce) requestHeaders.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) const response = NextResponse.next({ request: { headers: requestHeaders, }, }) response.headers.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) return response } ``` ```js filename="middleware.js" switcher import { NextResponse } from 'next/server' export function middleware(request) { const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const cspHeader = ` default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; style-src 'self' 'nonce-${nonce}'; img-src 'self' blob: data:; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; ` // Replace newline characters and spaces const contentSecurityPolicyHeaderValue = cspHeader .replace(/\s{2,}/g, ' ') .trim() const requestHeaders = new Headers(request.headers) requestHeaders.set('x-nonce', nonce) requestHeaders.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) const response = NextResponse.next({ request: { headers: requestHeaders, }, }) response.headers.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) return response } ``` By default, Middleware runs on all requests. You can filter Middleware to run on specific paths using a [`matcher`](/docs/app/api-reference/file-conventions/middleware#matcher). We recommend ignoring matching prefetches (from `next/link`) and static assets that don't need the CSP header. ```ts filename="middleware.ts" switcher export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ { source: '/((?!api|_next/static|_next/image|favicon.ico).*)', missing: [ { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }, ], }, ], } ``` ```js filename="middleware.js" switcher export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ { source: '/((?!api|_next/static|_next/image|favicon.ico).*)', missing: [ { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }, ], }, ], } ``` ### Reading the nonce You can provide the nonce to your page using [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props): ```tsx filename="pages/index.tsx" switcher import Script from 'next/script' import type { GetServerSideProps } from 'next' export default function Page({ nonce }) { return (