Content Security Policy
The CSP the kit enforces in production, how scripts are trusted, and how to allow third-party origins.
Production pages send a Content Security Policy that blocks the usual script injections: inline event handlers, javascript: URLs, eval, and scripts from origins you haven't allowed that aren't loaded by a trusted script. It's built per response by apps/web/middleware/03.security.ts (kit-owned) and extended in apps/web/config/security.config.ts (yours).
This page is part of the Security documentation.
The Policy
| Directive | Sources | Why |
|---|---|---|
default-src | 'self' | Anything not listed below: same origin only. |
script-src | 'self' 'strict-dynamic' 'nonce-…' + yours | Only scripts carrying this response's nonce run, plus scripts they load. |
style-src | 'self' 'unsafe-inline' | React style props and Base UI's inline <style> tags. |
img-src | 'self' data: blob:, plus the enabled social providers' avatar origins | Inline icons, local previews of uploads, and profile pictures (see Profile Pictures). |
font-src | 'self' data: | Bundled fonts. |
connect-src, frame-src, manifest-src, media-src | 'self' + yours | fetch, iframes, the manifest, audio and video. |
worker-src | 'self' blob: | Web workers. |
object-src, base-uri, frame-ancestors | 'none' | No plugins, no <base> hijacking, no framing (clickjacking). Not extendable from security.config.ts. |
form-action | 'self' + yours, plus https://checkout.stripe.com and https://billing.stripe.com with billing on | Forms post only to your app; the billing page's forms redirect to Stripe Checkout and the portal (a Stripe custom domain for Checkout goes in security.config.ts → csp). |
upgrade-insecure-requests | http: subresources load over https. Omitted on localhost, 127.0.0.1 and [::1]. |
security.config.ts pre-lists Cloudflare Turnstile (https://challenges.cloudflare.com) in script-src, frame-src and connect-src, for the auth forms' bot check.
Only HTML responses the Worker renders carry the policy. Local dev (pnpm dev) sends none, because Vite's dev scripts would violate it; vp preview and deployed Workers enforce it. Marketing pages requested without cookies are the one exception: see Cached Marketing Pages.
Cached Marketing Pages
Pages under apps/web/pages/(marketing)/ (the landing page, FAQ, legal pages) are meant to be served from Void's ISR cache. A nonce can't be shared between visitors, so when a request without cookies to one of these pages at its bare URL (/faq, not /it/faq) gets a response Void will store (status 200, no Set-Cookie, no private/no-store/no-cache, no Vary), 03.security.ts sends no CSP and no nonce and doesn't mark it private. Any other response keeps the nonce CSP. The other security headers (HSTS, nosniff, X-Frame-Options, Referrer-Policy, …) are always set; Void's ISR stores the headers of the response it caches, so cached copies carry them too.
- Locale prefixes keep the CSP: Void picks the cache lifetime from the URL before the locale rewrite, so
/it/faqis never cached; it renders live with the nonce CSP. See URL prefixes. - Who gets the cached page: Void serves cached HTML only to requests without a
Cookieheader, i.e. first visits and crawlers. Anyone with a cookie (signed in, or a saved theme or language) gets a live render with the nonce CSP, as on every other page. - The folder decides: moving a page into
pages/(marketing)/makes it cacheable; there's no per-page switch and no list to keep. The rule lives inapps/web/lib/cacheable-routes.server.ts(isCacheableRequest): a request counts only when the page that serves it is a marketing page, the most specific route winning (static over[param]over[...rest]), so a marketing[slug].tsxnever strips the CSP from/password-resetor/dashboard. A marketing route that another page ties with or outranks is never cached, andpnpm test:unitfails on it. - Keep these pages static: they render only content from the repo. Never read query parameters, request headers or user input in them, and never pass HTML to
dangerouslySetInnerHTML: with no CSP, an injection would run on your app's origin. A page that takes user input (a contact form, search, comments) belongs outsidepages/(marketing)/. - Links into the app reload the page: a visitor who lands on a cached page has a document without a CSP, and Void's client-side navigation keeps that document. Link from marketing pages to sign-in or app pages with
LocalizedLinkandreloadDocument(a full page load, so the new page gets its CSP); header and footer links fromconfig/marketing-navigation.config.tsalways do. - Analytics and embeds are allowed: script tags run for every visitor (cookieless responses have no CSP; the rest get the nonce). Add the script's request, image and frame origins to
security.config.ts→cspso they also work for visitors with cookies. Any cookie the script sets turns off caching for that visitor's later requests. - Deploys:
routing.isr: trueinapps/web/void.config.tsletsvoid deploycreate the ISR cache without asking.vp previewhas no ISR cache, so locally these pages render on each request;apps/e2e/tests/marketing/cacheability.spec.tsfinds every marketing page the way the app does and checks each one without cookies: noSet-Cookieorprivate/no-store/no-cache, the same HTML whateverHostorX-Forwarded-Hostis sent, and identicalsharedpage data withuser: nulland no nonce. A page you add is checked automatically (pages with[params]are skipped).
How Scripts Are Trusted
Every response gets a fresh random nonce. As the HTML streams out, the middleware adds nonce="…" to every <script> and <link rel="modulepreload"> in it, using Cloudflare's HTMLRewriter. That covers Void's bundle, the theme script, React's inline runtime and the scripts Void streams for defer() data, none of which can be hashed because their content changes per response.
'strict-dynamic' then trusts whatever those scripts load at runtime (code-split chunks, Turnstile's own scripts). In browsers that support it, 'self' and host sources in script-src are ignored; they only matter for older browsers.
What it blocks:
- Inline event handlers (
<img onerror="…">), whether rendered or added to the DOM later. javascript:URLs.eval,new Functionand stringsetTimeout.<script>tags added throughinnerHTML(browsers never run those anyway).
What it doesn't block: a <script> tag inside the server-rendered HTML gets the nonce like any other. If you render untrusted HTML with dangerouslySetInnerHTML, sanitize it first; the CSP won't save you there.
Adding a Third-Party Service
Example: an analytics service that loads https://cdn.example-analytics.com/script.js and sends events to https://events.example-analytics.com.
Add the origins to
apps/web/config/security.config.ts, under the directives the service needs:csp: {'script-src': [TURNSTILE, 'https://cdn.example-analytics.com'],'frame-src': [TURNSTILE],'connect-src': [TURNSTILE, 'https://events.example-analytics.com'],},Load the script with a
<script src>tag your app renders (e.g. throughdefineHead); it gets the nonce automatically. A snippet the vendor tells you to paste inline works the same way.Rebuild and run
vp preview, then open the browser console: any remaining violation names the directive and the blocked URL. Add that origin to that directive.
The script-src entry is for older browsers; img-src (tracking pixels) and connect-src (events) are what modern browsers check.
Never add *, 'unsafe-inline' or 'unsafe-eval' to script-src: 'unsafe-inline' is ignored next to a nonce anyway, and the other two reopen the attacks the policy exists to block.
The Worker refuses to start if security.config.ts does either: script-src with one of those three, or any source containing ; or ,. List one source per entry.
Profile Pictures
Members sign in with Google or GitHub, and Better Auth stores their profile picture URL as user.image. The members table and the account menu show it. So those images load, the kit adds each enabled social provider's avatar origin to img-src:
| Provider | Origin added |
|---|---|
google | https://lh3.googleusercontent.com |
github | https://avatars.githubusercontent.com |
twitter (X) | https://pbs.twimg.com, https://abs.twimg.com (the default picture) |
A provider counts when both of its keys are set (apps/web/config/auth.config.server.ts). Microsoft sends the picture as a data: URL, which is already allowed, and Apple sends none. Facebook isn't listed: its picture URLs redirect between CDNs and expire, so stored ones break anyway.
For another provider, set imageOrigins on its entry, next to its name and logo; it also replaces a listed provider's default:
discord: { clientId: env.AUTH_DISCORD_CLIENT_ID, clientSecret: env.AUTH_DISCORD_CLIENT_SECRET, name: 'Discord', logo: '/images/oauth/discord.svg', imageOrigins: ['https://cdn.discordapp.com'],},Each must be a plain https:// origin (no path, no *); anything else stops the Worker with the provider's name. Turning a provider off drops its origins, so members who signed up with it show their initial; to keep their pictures, list the origin under img-src in security.config.ts.
The origins come from that list and your entries, never from the stored image URLs: any user can set user.image, so allowing whatever host it names would let anyone add a tracking-pixel origin. For the same reason, never widen img-src to * or https:. A picture from an origin that isn't listed falls back to the member's initial.
Dev sends no CSP, so pictures load there either way: check with vp preview.
Billing (Stripe)
With both Stripe keys set, the kit adds Stripe Checkout and the Stripe portal to form-action, and nothing else: the billing page's plan buttons are plain form posts that the server redirects to Stripe, with no Stripe.js and no frames. Dev sends no CSP, so check it in the production preview:
- Put test-mode keys and one price per plan (
STRIPE_PRICE_*) inapps/web/.env, then runpnpm preview. It passes the Stripe andSTRIPE_PRICE_*keys to the Worker. - Open
/settings/billingas an owner and choose a plan. - Confirm the browser reaches Stripe Checkout and the console shows no
form-actionviolation.
Rolling Out: Report-Only
To try a policy change on a live environment without breaking anything:
void secret put CSP_MODEwithreport-only, then deploy. Responses sendContent-Security-Policy-Report-Onlyinstead: nothing is blocked, violations appear in the browser console.- Browse every page that changed and fix each violation reported in the console.
- Set
CSP_MODEback toenforce(or delete the secret;enforceis the default).
CSP_MODE=off sends no policy at all. Use it only to rule out the CSP while debugging. There's no violation report endpoint.
Troubleshooting a Violation
A blocked resource shows in the console as Refused to load the script 'https://…' because it violates the following Content Security Policy directive: "script-src …" (wording varies by browser).
- A URL was refused: add its origin to the directive named in the message, in
security.config.ts. - An inline handler was refused (the event reports it as
script-src-attr; the console namesscript-src): replaceonclick="…"markup with a React event handler. evalwas refused: a library is compiling code at runtime. Use its CSP-safe build, or replace the library.- zod and
eval: zod 4 probes forevalwhen it builds a schema. With the CSP on,03.security.tssets zod'sjitlessoption in a nonce'd head script before any module runs, so the probe never runs and nothing is reported; zod behaves the same, since the CSP blocksevalanyway (inreport-onlyit gives up zod's compiled fast path, a speed cost only). - Base UI's
renderBeforeHydrationonTabs.IndicatororSlider.Thumbrenders an inline script; it gets the nonce, so it works. - A page needs its own policy: set
Content-Security-Policy(or-Report-Only) in its handler. The middleware then leaves that response alone, without a nonce, so your policy must allow its scripts another way, including the kit's inline theme and zod scripts.
Common Pitfalls
- Expecting CSP in
pnpm dev: test withvp previewinstead. - Overriding
CSP_MODEin localvp preview: preview passes only the required keys to the Worker, so a localCSP_MODEvalue is ignored there. - ISR and edge caching: a cached page would hand the same nonce to every visitor, so the middleware marks each nonced page
Cache-Control: private(unless it already saysprivate,no-storeorno-cache). Void's ISR then skips those pages. To cache a public page, put it inpages/(marketing)/(Cached Marketing Pages). - Prerendering a page outside
pages/(marketing)/: its cookieless render is nonced andprivate, so Void never stores it; theprerenderexport does nothing there.
Next: CSRF Protection →