A Next.js app that just got its framework patched can still fall to XSS or be framed by a hostile site if the server doesn't send the right security headers. They take little effort, yet they are usually forgotten until an enterprise customer sends back a penetration test report. This guide sets up Next.js security headers in two layers: static headers and a nonce-based Content Security Policy (CSP). It targets Next.js 16 with the App Router and is checked against the official Next.js documentation.

Two layers: static headers and per-request headers

Not every header is set the same way. Most have fixed values you define once in configuration. A nonce-based CSP, however, needs a fresh value on every request, so code has to run before the page is rendered.

LayerHeadersWhere to configure
StaticX-Content-Type-Options, Referrer-Policy, Strict-Transport-Security, Permissions-Policyheaders() in next.config.js
DynamicContent-Security-Policy with nonceproxy.ts in the project root

In Next.js 16 the file that runs before a request is called proxy.ts (the current CSP guide uses this name and a proxy function). On an older version, follow the docs for your version, since the file name may differ.

Static headers in next.config.js

The docs describe the headers key as a function returning an array of objects with a source (path pattern) and headers (a list of key and value). The example below applies to every path:

// next.config.js
module.exports = {
  headers() {
    return [
      {
        source: '/:path*',
        headers: [
          { key: 'X-Content-Type-Options', value: 'nosniff' },
          { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
          {
            key: 'Strict-Transport-Security',
            value: 'max-age=63072000; includeSubDomains',
          },
          {
            key: 'Permissions-Policy',
            value: 'camera=(), microphone=(), geolocation=()',
          },
        ],
      },
    ]
  },
}

Each line does one job:

  • nosniff stops the browser from guessing file types, so an uploaded file can't be executed as a script.
  • Referrer-Policy limits how much of your URL is passed to other sites, so order IDs or tokens in a path don't leak through the Referer header.
  • Strict-Transport-Security forces HTTPS. Enable it only once the domain and every subdomain run stable HTTPS, because browsers remember it for a long time.
  • Permissions-Policy switches off device permissions the app doesn't use.

One easy trap: the docs state that when two blocks match the same path and set the same key, the later block overrides the earlier one. When you add a route-specific block, re-check which header is actually sent.

CSP with a nonce: block foreign scripts, keep your own

CSP tells the browser which origins may load scripts, styles, images and fonts. Per the Next.js docs, a nonce is a random, single-use string; only scripts carrying the matching nonce run, so an attacker who injects a script tag still can't execute it. The nonce must be unpredictable and different on every request.

The code below comes from the docs example, trimmed slightly:

// proxy.ts
import { NextRequest, NextResponse } from 'next/server'

export function proxy(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
  const isDev = process.env.NODE_ENV === 'development'
  const csp = `
    default-src 'self';
    script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ''};
    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', csp)

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

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' },
      ],
    },
  ],
}

What to notice:

  1. The nonce comes from crypto.randomUUID(), base64-encoded, one value per request.
  2. 'strict-dynamic' lets a nonced script load further scripts, so the Next.js bundles still run.
  3. 'unsafe-eval' is added only in development because React uses eval for debugging details. The docs say production doesn't need it.
  4. frame-ancestors 'none' prevents other sites from framing yours (clickjacking); object-src 'none' blocks legacy plugins.
  5. The matcher skips API routes, static files and prefetch requests to avoid pointless work.

The nonce requires dynamic rendering

This is the real trade-off. The docs stress that using nonces means pages must be rendered dynamically, because a new nonce is needed on every view. A page pre-built at build time can't carry a matching nonce. For a mostly static marketing site, decide deliberately: accept dynamic rendering, or use a looser CSP without nonces. Write that decision down in the project's technical notes.

If you use third-party scripts such as analytics or chat widgets, give their script tags the nonce and list their domains explicitly rather than loosening default-src for everything.

Verify the result and fix the usual problems

After deploying, check with:

curl -sI https://your-domain.example | grep -iE 'content-security|strict-transport|x-content-type|referrer|permissions'

Then open DevTools and the Console: the browser logs every CSP violation along with the blocked directive.

Common problems:

  • Blank page or dead buttons after enabling CSP: usually an inline script without a nonce, or a third-party source not yet allowed.
  • A header missing on one route: check whether the matcher accidentally excludes it, or another config block overrides it.
  • HSTS enabled while a subdomain still serves HTTP: users will be locked out of that subdomain. Start with a short max-age.
  • eval errors in dev: confirm NODE_ENV is handled as in the code above.

Put that curl check into your post-deploy CI step so the headers don't silently disappear when someone edits the configuration.

Headers are one layer, not a substitute for framework patches

Headers limit the damage when the application has a flaw, but they don't replace upgrading. Next.js ships security releases on a regular schedule; the November 2026 release landed in 16.4.5 and 15.5.29. The article Next.js 51 advisory in 2026: how to keep apps safe (Vietnamese) explains how to track those patches. If your app shares a stack with Payload CMS, the same header set applies to the front end and the admin panel, but test carefully because the admin has its own scripts.

About to take a Next.js app to production, or just received a pentest report? Run the curl check above against the live environment first, then share the output with your engineers or contact Besoft to review it together.

References