Setting a Content Security Policy (CSP) in Next.js – Nonces, Proxy Headers, and Dynamic Rendering

Content Security Policy (CSP) protects your Next.js application from XSS, clickjacking, and injection attacks. This article explains how to configure CSP headers using Proxy, generate nonces for inline script safety, and enforce dynamic rendering to support nonce-based security.

Content Security PolicyNonceProxyDynamic RenderingContent Security PolicyNonceProxy

~3 دقیقه مطالعه · آخرین به‌روزرسانی ۴ آبان ۱۴۰۴

Why Use a Content Security Policy?


CSP helps prevent cross-site scripting (XSS), clickjacking, and other injection attacks by restricting which sources can load content, scripts, styles, fonts, media, and more. It’s a critical layer of defense for modern web applications.


What Is a Nonce?


A nonce is a unique, random string generated per request. It allows specific inline scripts or styles to bypass strict CSP rules. Because the nonce changes with every request, attackers cannot predict or reuse it.


Adding a Nonce with Proxy


Use proxy.ts to generate a nonce and inject it into the CSP header:

export function proxy(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(/\s{2,}/g, ' ').trim()

  const requestHeaders = new Headers(request.headers)
  requestHeaders.set('x-nonce', nonce)
  requestHeaders.set('Content-Security-Policy', cspHeader)

  const response = NextResponse.next({ request: { headers: requestHeaders } })
  response.headers.set('Content-Security-Policy', cspHeader)

  return response
}

Proxy Matcher Configuration


Exclude static assets and prefetches from CSP enforcement:

export const config = {
  matcher: [
    {
      source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
      missing: [
        { type: 'header', key: 'next-router-prefetch' },
        { type: 'header', key: 'purpose', value: 'prefetch' },
      ],
    },
  ],
}

How Nonces Work in Next.js


  • Proxy generates a nonce and sets it in the CSP and x-nonce headers
  • Next.js extracts the nonce from the CSP header during rendering
  • Nonce is automatically applied to:
    • React and Next.js runtime scripts
    • Page-specific JavaScript bundles
    • Inline styles/scripts generated by Next.js
    • <Script> components using the nonce prop

Forcing Dynamic Rendering


To support nonce injection, pages must be dynamically rendered. Use connection() to wait for a request:

import { connection } from 'next/server'

export default async function Page() {
  await connection()
  // Page content
}

Reading the Nonce in Server Components


Use headers() to access the nonce:

import { headers } from 'next/headers'
import Script from 'next/script'

export default async function Page() {
  const nonce = (await headers()).get('x-nonce')

  return (
    <Script
      src="https://www.googletagmanager.com/gtag/js"
      strategy="afterInteractive"
      nonce={nonce}
    />
  )
}

Static vs Dynamic Rendering with CSP


Nonce-based CSP requires dynamic rendering. This disables:

  • Static optimization
  • Incremental Static Regeneration (ISR)
  • CDN caching
  • Partial Prerendering (PPR)

Performance Implications


  • Slower initial page loads
  • Increased server load
  • Higher hosting costs

When to Use Nonces


  • Strict security policies prohibit 'unsafe-inline'
  • Your app handles sensitive data
  • You need selective inline script execution
  • Compliance requires strict CSP enforcement

Conclusion


Setting a Content Security Policy with nonces in Next.js strengthens your app’s security posture. While it requires dynamic rendering and may impact performance, it’s essential for applications with strict security or compliance needs.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه