skip to content

cat ./blog/strict-csp-nextjs-pure-function.mdx

A Strict Content Security Policy in Next.js 16, Built as a Pure Function

10 min readnextjstypescriptcsp

All source code for this post is available at https://github.com/braveneworg/braveneworg.com.

A strict Content Security Policy is the last line of defense against cross-site scripting. If someone gets a <script> tag into your page, through a comment field, a compromised dependency or a rich text editor, the browser refuses to run it. Most of the policies I come across are either missing or carry 'unsafe-inline' in script-src, which protects about as well as no policy.

braveneworg.com, the site I built for my web development business, sends a nonce-based policy on every page, with a nonce that changes on every request. This post shows the two files that do it, why they are split the way they are, and what a strict policy costs you in Next.js. If you are adding a CSP to an App Router site, you can lift most of this.

Stack: Next.js 16.4 (App Router, proxy.ts, Cache Components on), React 19.2, Payload CMS 3 in the same app, Sentry's Next.js SDK 11, deployed on Vercel. I assume you know your way around response headers and have seen a CSP before. If you haven't seen it, it ends up a header that looks something like this (with line breaks for readability):

Shell
Content-Security-Policy:
  default-src 'self';
  script-src 'self'
  'nonce-ZDdkOTMxMTYtNTIyZC00OTE0LWE4MDItZjE0MmVmYmQxNjdl'
  'strict-dynamic' https://challenges.cloudflare.com https://js.stripe.com https://*.js.stripe.com https://www.googletagmanager.com;
  frame-src https://challenges.cloudflare.com https://js.stripe.com https://*.js.stripe.com https://hooks.stripe.com;
  img-src 'self' data: https://r2ikmqdkbcvnkdnt.public.blob.vercel-storage.com https://www.googletagmanager.com
  https://*.google-analytics.com; connect-src 'self' https://challenges.cloudflare.com https://api.stripe.com
  https://vitals.vercel-insights.com https://www.googletagmanager.com https://*.google-analytics.com
  https://*.google.com https://o4512504684937216.ingest.us.sentry.io;
  worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; font-src
  'self'; object-src 'none'; frame-ancestors 'self'; base-uri 'self';
  form-action 'self'

Why a nonce

The old way to write a CSP was a list of hosts: scripts may come from my own site and from these five domains. That fails in two ways. Any script hosted anywhere on an allowed domain is allowed, including ones you never meant. And inline scripts, which Next.js needs to hydrate a page, are either all allowed with 'unsafe-inline' or all refused.

A nonce fixes both. The server makes up a random value for each response, puts it in the header, and puts the same value on every <script> tag it renders. The browser runs a script only if its nonce matches the header. An injected script does not know the value, because it was made up after the attacker wrote the malicious payload.

The policy is a function that returns a string

The whole policy is built by one function with no side effects. It reads nothing from the environment, it touches no request, and it returns a string.

TypeScript
export const buildCsp = ({
  nonce,
  isDev,
  mediaHost,
  framesYouTube = false,
  googleAnalytics = false,
  sentryIngest,
}: CspOptions): string =>
  [
    "default-src 'self'",
    [
      "script-src 'self'",
      `'nonce-${nonce}'`,
      "'strict-dynamic'",
      TURNSTILE,
      STRIPE_JS,
      STRIPE_JS_ANY,
      ...(googleAnalytics ? [GOOGLE_TAG_HOST] : []),
      ...(isDev ? ["'unsafe-eval'"] : []),
    ].join(' '),
    ['frame-src', TURNSTILE, STRIPE_JS, STRIPE_JS_ANY, STRIPE_HOOKS, ...(framesYouTube ? [YOUTUBE] : [])].join(' '),
    [
      "img-src 'self' data:",
      ...(mediaHost ? [mediaHost] : []),
      ...(googleAnalytics ? [GOOGLE_TAG_HOST, GOOGLE_ANALYTICS_HOSTS] : []),
    ].join(' '),
    connectSrc({ googleAnalytics, sentryIngest }),
    ...(sentryIngest ? ["worker-src 'self' blob:"] : []),
    "style-src 'self' 'unsafe-inline'",
    "font-src 'self'",
    // Nothing on the site uses `<object>` or `<embed>`; left out, they would
    // fall back to `default-src` and load anything the site itself serves.
    "object-src 'none'",
    // 'self', not 'none': the admin's Live Preview pane frames site pages
    // from the same origin. No other site may frame them.
    "frame-ancestors 'self'",
    "base-uri 'self'",
    "form-action 'self'",
  ].join('; ');

A CSP header is a list of directives separated by semicolons, and each directive is a list of sources separated by spaces. The code is shaped the same way: an outer array joined with '; ', and inner arrays joined with ' '. You can read the policy top to bottom without parsing a template string in your head.

One directive, connect-src, collected enough conditions to earn a helper of its own. It is built the same way and returns one directive as a string:

TypeScript
const connectSrc = ({ googleAnalytics, sentryIngest }: Pick<CspOptions, 'googleAnalytics' | 'sentryIngest'>): string =>
  [
    "connect-src 'self'",
    TURNSTILE,
    STRIPE_API,
    VERCEL_VITALS,
    ...(googleAnalytics ? [GOOGLE_TAG_HOST, GOOGLE_ANALYTICS_HOSTS, GOOGLE_HOSTS] : []),
    ...(sentryIngest ? [sentryIngest] : []),
  ].join(' ');

Pick<CspOptions, ...> keeps the helper's parameter tied to the options type, so renaming an option is one change and the helper cannot be handed something the policy does not know about.

Three techniques in here are worth naming.

Conditional spreads. ...(googleAnalytics ? [GOOGLE_TAG_HOST] : []) adds a source only when a condition holds, and adds nothing at all when it does not. There is no empty string to filter out and no trailing space. Every optional part of the policy is written this way, and it works one level up as well: ...(sentryIngest ? ["worker-src 'self' blob:"] : []) adds or omits a whole directive.

Options, not environment. The function takes an options object. It never reads process.env and never looks at a request. The caller decides whether this is development, whether analytics is on, and whether this page may frame YouTube. That makes the function trivial to test: pass options, compare the string. It also makes each permission visible at the call site.

Permissions are as narrow as the feature. Google's hosts are in the policy only if a measurement ID is configured. With analytics off, the header does not name Google at all. Sentry is handled the same way. Its ingest origin joins connect-src only once a DSN is set, and the same switch adds worker-src 'self' blob:, which Session Replay needs to start its compression worker from a blob URL. Sentry gets no entry in script-src, because its browser SDK ships as one of the site's own chunks. YouTube may be framed by exactly one page on the site. The media host is added only when uploads live on another origin. 'unsafe-eval' appears only in development, where React uses it to rebuild server error stacks. A policy grows by one line per third party, and each line here has a condition and a comment saying why it exists.

What 'strict-dynamic' buys

'strict-dynamic' says: a script that carries the nonce may load other scripts, and those are trusted too. Next.js loads its chunks this way. So does Stripe.js, and so does Cloudflare's Turnstile widget. Without it you would have to list every host any of them might load from, and keep that list current.

In a browser that understands 'strict-dynamic', the host names beside it in script-src are ignored. They are there for older browsers that do not understand it, which fall back to the list. The comment above the function says so, because the next person to read the policy will otherwise wonder why both are there.

What I did not lock down

style-src allows 'unsafe-inline'. Inline styles are a much smaller risk than inline scripts, and a nonce cannot cover a style attribute, which frameworks and third-party widgets set freely. I chose to say so plainly in the policy over pretending. A CSP that is strict about scripts and honest about styles is far better than no CSP.

The proxy: one nonce, set twice

In Next.js 16 the file that runs before every request is proxy.ts (earlier versions called it middleware). Mine is short.

TypeScript
export const proxy = (request: NextRequest): NextResponse => {
  const guarded = guardAdminLoginPage(request);

  if (guarded) {
    return withBaseHeaders(guarded);
  }

  const { pathname } = request.nextUrl;

  if (!usesStrictPolicy(pathname)) {
    const response = NextResponse.next();
    response.headers.set('Content-Security-Policy', ADMIN_CSP);
    return withBaseHeaders(response);
  }

  const dsn = sentryDsn(process.env.NEXT_PUBLIC_SENTRY_DSN);
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
  const csp = buildCsp({
    nonce,
    isDev: process.env.NODE_ENV === 'development',
    mediaHost: blobOrigin(blobToken(process.env)),
    framesYouTube: pathname === LOGIN_CHALLENGE_FAILED_PATH,
    googleAnalytics: googleAnalyticsId() !== undefined,
    sentryIngest: dsn === undefined ? undefined : sentryIngestOrigin(dsn),
  });

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set(NONCE_HEADER, nonce);
  requestHeaders.set('Content-Security-Policy', csp);

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

  return withBaseHeaders(response);
};

The proxy is where the environment gets read, so buildCsp never has to. Look at the Sentry line: sentryDsn validates the environment variable and returns undefined for anything that is not a well-formed DSN, and sentryIngestOrigin is new URL(dsn).origin. A DSN carries a key in its userinfo part. The key is public, but the browser only needs the origin to enforce the policy, so the origin is all the header gets.

The part people get wrong is the last few lines. The policy is set in two places, and each one has a different reader.

The response header is for the browser. That is the policy it enforces.

The request headers are for the render. Next.js reads the Content-Security-Policy header on the incoming request, finds the nonce in it, and puts that nonce on every script tag it generates: the framework's own chunks, the hydration data, and anything loaded through next/script. The app's own code reads the same nonce from a second request header, x-nonce, for the script tags it writes itself.

If you set only the response header, the browser enforces a policy whose nonce is on no script, and the page does not hydrate. If you set only the request headers, the scripts carry a nonce and the browser was never told to check it.

Reading the nonce in a Server Component is one line, wrapped so nothing else needs to know the header's name:

TypeScript
export const getNonce = async (): Promise<string | undefined> => (await headers()).get(NONCE_HEADER) ?? undefined;

The root layout calls getNonce() once and passes the value to the components that render a script: the JSON-LD block, the analytics loader, the captcha widget.

Two policies for two apps

The site shares its Next.js app with Payload, the CMS, which serves an admin at /admin and an API at /api. The admin loads its own scripts and knows nothing about the site's nonce. A strict policy would break it.

TypeScript
const PAYLOAD_PATHS = /^\/(admin|api)(\/|$)/;

export const usesStrictPolicy = (pathname: string): boolean => !PAYLOAD_PATHS.test(pathname);

So the proxy branches. Admin and API paths get a policy with one directive, frame-ancestors 'self', which stops another site from framing the admin for a clickjacking attack. Everything else gets the strict policy. Both get the baseline headers: HSTS, nosniff, a referrer policy and a permissions policy.

The regular expression ends in (\/|$) for a reason. Without it, a public page at /administration or /api-guide would match and silently lose its strict policy. Anchoring the end means only /admin, /admin/..., /api and /api/... are exempt.

The HSTS header covers this host only, for two years. It leaves out includeSubDomains and preload on purpose. Those bind every subdomain to HTTPS for years, and a preload entry is slow to undo. Add them once you have confirmed each subdomain serves HTTPS, not before.

Skip what does not need it

TypeScript
export const config = {
  matcher: [
    {
      // Static files and image optimisation need no policy; link prefetches
      // skip the proxy as the CSP guide recommends.
      source: '/((?!_next/static|_next/image|favicon.ico).*)',
      missing: [
        { type: 'header', key: 'next-router-prefetch' },
        { type: 'header', key: 'purpose', value: 'prefetch' },
      ],
    },
  ],
};

A TypeScript file or an optimized image is not a document, so a CSP on it does nothing. The matcher skips those, and it skips link prefetches, as the Next.js CSP guide recommends. My matcher differs from the guide's example in one way: it does not exclude /api. Those paths still go through the proxy so they receive the baseline headers and the framing rule.

What it costs

A nonce is made up per request, so a page that carries one cannot be built ahead of time. The Next.js guide is direct about this: with a nonce-based policy, every page must be rendered dynamically, and partial prerendering is incompatible, because a static shell is built before any request exists and cannot hold that request's nonce.

The root layout states the trade in a comment and one export:

TypeScript
// Every page renders per request so the CSP nonce reaches its scripts, and
// Cache Components' Partial Prerendering cannot carry a nonce in a static
// shell. `false` lets this root layout block on its reads instead of
// prerendering a shell (see `instant.md` and `content-security-policy.md` in
// node_modules/next/dist/docs). Content stays fast: the repositories cache it.
export const instant = false;

The last sentence of that comment is how I pay for it. The HTML is rendered per request, but the data it is rendered from is cached. Every read from the CMS goes through a cached function with tags, so a request does a render and no database work. Rendering a page from cached data is quick. What you give up is serving the HTML itself from a CDN edge.

For a marketing site with a contact form and a payment step, I think a real script policy is worth that. If your pages must be static, Next.js has experimental hash-based CSP support that keeps static generation. It is a different trade and worth reading about before you choose.

Testing a header

Because buildCsp is pure, most of the tests are a function call and an assertion on a string. The proxy's tests then check the wiring, and their names read as the policy's promises:

  • "makes a fresh nonce for every request"
  • "hands the nonce and the policy to the render, so Next.js can nonce its own scripts"
  • "names no Google host while Google Analytics is off"
  • "names no Sentry host while Sentry is off"
  • "allows Sentry's ingest host, not the DSN's key, once a DSN is set"
  • "frames YouTube on the failed login challenge only"
  • "skips static assets, image optimisation and link prefetches"

Unit tests cannot tell you whether a real browser reports a violation. For that, listen for the securitypolicyviolation event in an end-to-end test. That is how I found that Zod 4 probes new Function when it first builds a schema. Zod handles the refusal, but the browser still logs it and Lighthouse still counts it. The event's sourceFile named the chunk, and one line of Zod configuration fixed it.

What to take from it

  • Build the policy with a pure function that takes options. Test the string.
  • Write the directives as arrays and add optional sources with conditional spreads.
  • Give each third party the narrowest permission, behind the condition that makes it necessary, with a comment that says why.
  • In the proxy, set the policy on the request headers for the render and on the response headers for the browser.
  • Exempt the paths that cannot carry your nonce with an anchored pattern, and still send them the baseline headers.
  • Know the cost. A nonce means dynamic rendering, so cache the data underneath.

cat ./comments

comments (0)

no comments yet — start the thread

leave a comment