brokeinprod
brokeinprod
Theme

Security

A Content-Security-Policy for Next.js That Doesn't Break YouTube, Turnstile, or Your Analytics

A working Content-Security-Policy for a Next.js site with embedded YouTube, Cloudflare Turnstile, and Vercel Analytics, explained directive by directive.

November 26, 2026

I turned on a strict CSP. Every embedded video, the bot protection on the contact form, and the analytics went dark in the same page load.

Start here: First pick your tier: a strict nonce-based CSP via middleware (best protection, but it forces dynamic rendering) or a pragmatic static CSP in next.config headers with 'unsafe-inline' (simpler, keeps static rendering, weaker). Then allowlist each third party: Cloudflare Turnstile in script-src, connect-src, and frame-src, the YouTube player in frame-src, YouTube thumbnails in img-src, and the Vercel Analytics script and intake hosts. Server-side APIs like Resend do not belong in connect-src.

The setup

I wanted a real Content-Security-Policy on this site, the header that tells the browser which origins may load scripts, styles, images, frames, and so on. It is one of the most effective settings available against cross-site scripting and clickjacking. It is also the setting most likely to break your site silently, because the moment you go strict, everything you did not explicitly allow stops loading.

This site is not a plain brochure page. It embeds YouTube videos, runs Cloudflare Turnstile on its forms, and reports Web Vitals to Vercel Analytics. Each of those is a third party the browser has to be told to trust. So "add a CSP" means "enumerate every external thing your app legitimately does, and nothing more."

The first decision that determines everything: nonce vs. 'unsafe-inline'

Before any directive, you have to make one architectural choice, because the rest of your CSP hangs off it.

Next.js injects inline scripts to bootstrap the App Router. A strict CSP forbids inline scripts unless each one carries a matching nonce, a fresh random token generated per request. Next.js supports this, with a catch worth understanding: a nonce can only be applied during server-side rendering, so using nonces forces your pages to render dynamically. Statically generated pages have no request at build time, so there is no nonce to inject. There is also a development-only wrinkle: 'unsafe-eval' is required in dev because React uses eval for better error stacks.

That leaves two tiers:

  • Strict (nonce-based, via middleware): script-src 'self' 'nonce-…' 'strict-dynamic'. Best protection. Cost: you give up static rendering on those routes and take on middleware complexity.
  • Pragmatic (static, via next.config headers): script-src 'self' 'unsafe-inline' …. Simple, keeps static rendering, but 'unsafe-inline' weakens the XSS protection you came for.

This site uses the pragmatic tier, a static policy in next.config.ts. I am saying so plainly because most "secure CSP" posts present the config-headers approach as if it were strict. It is not. It is a reasonable tradeoff for a content site, but know which one you are shipping.

The policy, directive by directive

Here is the production policy, with each line explained by what it is for. Reasoning beats copy-pasting, because your third parties will not be identical to mine.

next.config.ts
 
 
{
  key: 'Content-Security-Policy',
  value: [
    "default-src 'self'",
    "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://challenges.cloudflare.com https://*.vercel-scripts.com",
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' data: blob: https://img.youtube.com https://*.ytimg.com https://<your-store>.public.blob.vercel-storage.com",
    "font-src 'self' data:",
    "connect-src 'self' https://api.resend.com https://challenges.cloudflare.com https://*.vercel-insights.com",
    "media-src 'self' blob:",
    "frame-src 'self' https://www.youtube.com https://youtube.com https://challenges.cloudflare.com",
    "frame-ancestors 'self'",
    "form-action 'self'",
    "base-uri 'self'",
    "object-src 'none'"
  ].join('; ')
}
  • default-src 'self': the fallback for anything not named below, your own origin only. Everything else is an explicit exception to this.
  • script-src: challenges.cloudflare.com is Turnstile's script; *.vercel-scripts.com is the Vercel Analytics script. The 'unsafe-inline' and 'unsafe-eval' entries are the pragmatic-tier cost discussed above.
  • img-src: img.youtube.com and *.ytimg.com are YouTube thumbnails. data: and blob: cover inline and generated images. Optimized next/image images are served same-origin from /_next/image, so they are already covered by 'self', and the public pages never needed the Blob host here. It is listed for one reason: the admin upload component shows a preview with a plain <img> tag, and that is the one place an image bypasses the optimizer. If you have no such path, leave your image host out. The companion piece on the unconfigured host error explains the mechanism.
  • connect-src: XHR, fetch, and WebSocket targets. Turnstile needs this; Vercel's Web Vitals beacon needs an insights host.
  • frame-src: who may be embedded in an iframe, the YouTube player and the Turnstile challenge frame.
  • frame-ancestors 'self': who may embed you (anti-clickjacking).
  • object-src 'none', base-uri 'self', form-action 'self': close off legacy plugin, <base>-hijacking, and form-exfiltration vectors. Cheap wins. Always include them.

Two things to fix or verify in the above

This is the part most articles skip, and it is the part that builds trust with a technical reader.

  1. connect-src https://api.resend.com: it is still in the shipped policy, and it should come out. Resend is called server-side from a route or server action; the browser never talks to api.resend.com directly, so the entry does nothing except suggest a client-side call that does not exist. It is harmless and it is wrong, which is the kind of line that outlives its reason. If you find yourself adding a third-party API host to connect-src, check whether you are calling it from the server, where CSP does not apply.
  2. The Vercel Analytics hosts are version-sensitive. Older setups needed *.vercel-scripts.com (script) and a vercel-insights host (connect). Current Speed Insights serves its script and ingests its data first-party, from a path under your own domain, which 'self' already covers; Vercel's own migration note says a CSP entry for the third-party script is no longer required. The two Vercel hosts in my policy are legacy and can come out. Check the current Vercel doc and your browser console rather than trusting any blog's frozen list, including this one.

How to roll it out without locking yourself out

  • Start in report-only mode (Content-Security-Policy-Report-Only) so violations are logged, not enforced. Watch the console, find what breaks, then flip to enforcing.
  • Open every interactive surface, embedded video, the contact form, anything with a widget, and watch DevTools for Refused to … messages. Each one names the directive and the blocked origin. That is your to-do list.
  • next.config header changes need a dev-server restart to take effect.

A CSP is not a wall of tokens. It is an inventory of everything your app legitimately reaches for, written down once, in a form the browser enforces.

FAQ

Do I need a nonce? Only for a strict CSP. Nonces require dynamic rendering, since Next.js injects them per request. The static 'unsafe-inline' policy is simpler but weaker.

Why is my embedded YouTube video blocked? The player iframe needs frame-src to include the YouTube domain, and the thumbnails need img-src to include the ytimg host. They are two separate directives.

Does CSP apply to my server-side Resend (or other API) calls? No. CSP governs the browser. Server-side API calls are not subject to it, which is why api.resend.com does not belong in connect-src.

Further reading

Keep reading

Newsletter

New posts in your inbox. No spam — unsubscribe anytime.

Occasional emails when we publish something worth your time. Unsubscribe anytime.

More about what you'll get on the newsletter page.

THEME
↑↓ navigate↵ openesc close