How to add a Content Security Policy to a React + Vite app
Last reviewed November 4, 2026 against the providers' current documentation.
The short version
Build the app, check that every <script> in dist/index.html has a src, and start from default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self', plus data: for images and fonts (Vite inlines small files as data: URIs) and your Supabase, Stripe or API addresses in connect-src. Send it from your host as Content-Security-Policy-Report-Only, click through the app, add what's legitimately missing, then rename the header to Content-Security-Policy. Never put data: or 'unsafe-inline' in script-src.
Why it matters
A Content Security Policy is a response header that tells the browser where scripts, styles, images and network requests may come from. If someone manages to inject markup into your app (a comment field rendered as HTML, a compromised script tag), the browser refuses to run a script the policy doesn't allow. MDN's CSP guide explains that once a policy has default-src or script-src, inline scripts, inline event handlers like onclick="...", javascript: URLs and eval() are blocked unless you allow them. That's the protection, and also why a careless policy can break an app. CSP is defense in depth, as Google's web.dev strict CSP article stresses: it limits the damage of an XSS bug, it doesn't replace fixing it. A Vite single-page app is a good fit, because a production build loads its code from files on your own domain.
Fix it, in this order
See what your site sends now
Run our free headers check on your live address. If it shows No Content Security Policy, your host isn't sending one. You can also press F12, open the Network tab, reload, click the first request and look forcontent-security-policyin its Response Headers.Look at your built index.html
Runnpm run buildand opendist/index.html. Vite's production build loads your app from files indist/assets/through<script type="module" src="...">tags, whichscript-src 'self'covers. Look for anything else: an inline<script>someone pasted intoindex.html(analytics snippets, chat widgets),onclick=attributes, or scripts from other domains. Move inline code into a file undersrc/and import it, or allow that exact inline script by its hash ('sha256-...'); web.dev recommends hashes for single-page apps that aren't server-rendered, but a hash changes whenever the script does. MDN notes that hashes and nonces don't cover inline event handlers, so replace those withaddEventListener. Add each external script's domain toscript-src.Start from this policy
This fits a typical Lovable or Bolt app (Vite, React, Supabase). ReplaceYOUR-PROJECTwith your Supabase project ref:
What the less obvious lines are for: Vite's docs say a build inlines small assets asdefault-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self' https://YOUR-PROJECT.supabase.co wss://YOUR-PROJECT.supabase.co; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'data:URIs, soimg-srcandfont-srcneeddata:(or setbuild.assetsInlineLimit: 0), and they warn never to allowdata:inscript-src.connect-srclists where your app sends requests; Supabase's Realtime connects towss://YOUR-PROJECT.supabase.co, so keep thewss://entry only if you use Realtime.style-src 'unsafe-inline'is there because many UI libraries add<style>tags at runtime; MUI's CSP guide, for example, says nonces aren't possible on static hosting and recommends'unsafe-inline'for styles there. It's a much smaller risk than inline scripts, and you can try removing it once the policy is enforced.img-src https:allows images from any https site; list exact domains instead if you prefer. If you use Stripe.js, add Stripe's own list:https://js.stripe.com https://*.js.stripe.comtoscript-srcandframe-src(plushttps://hooks.stripe.cominframe-srcfor 3D Secure), andhttps://api.stripe.comtoconnect-src. A redirect to Stripe Checkout is a normal page navigation and needs none of these.Test it locally with vite preview
The dev server (npm run dev) isn't what visitors get, so test the production build. Vite'spreview.headersoption sets response headers forvite preview:
Open the preview address, then use the app the way users do: sign up, log in, load data, upload, pay. In Chrome, DevTools reports each CSP violation as an issue; in report-only mode it's a warning and nothing breaks. Every legitimate request you see blocked is a source to add to the matching directive.// vite.config.js: test the policy locally with `npm run build && npx vite preview` import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' const csp = [ "default-src 'self'", "script-src 'self'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob: https:", "font-src 'self' data:", "connect-src 'self' https://YOUR-PROJECT.supabase.co wss://YOUR-PROJECT.supabase.co", "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'self'", ].join('; ') export default defineConfig({ plugins: [react()], preview: { headers: { 'Content-Security-Policy-Report-Only': csp }, }, })Send it from your host, report-only first
The policy only protects visitors when your host sends it as a response header. On Netlify, put it in a_headersfile in Vite'spublic/folder (see our Netlify headers guide); on Vercel, invercel.json(see our Vercel headers guide); our headers check page has the config for Cloudflare, Firebase, Amplify, nginx and Apache. Write the policy on one line, separating directives with;, and send it asContent-Security-Policy-Report-Only. A<meta http-equiv="Content-Security-Policy">tag inindex.htmlis a fallback only: MDN says a report-only policy can't be delivered in a meta tag, andframe-ancestorsisn't supported there. To collect reports from real visitors rather than your own browser, MDN describes adding aReporting-Endpointsheader and areport-todirective pointing at an endpoint you control.Enforce it, then tighten
When a few days of use show no legitimate violations, rename the header toContent-Security-Policyand deploy. If a library then needs'unsafe-eval', find out which one first: MDN says developers should avoid'unsafe-eval', so prefer a build or library that doesn't useeval()ornew Function. The strongest setup is what web.dev calls a strict CSP:script-src 'nonce-{random}' 'strict-dynamic', with a fresh nonce on every response. Vite supports it with thehtml.cspNonceoption, which puts a placeholder nonce on the script and style tags it generates; Vite's docs warn that the placeholder must be replaced with a unique value for each request. A plain static host can't do that, so you need a server or edge function (Netlify, for example, offers a CSP nonce extension that does it at the edge). For most static Vite apps, the policy above without'unsafe-inline'inscript-srcis the practical goal. Google's CSP Evaluator gives a second opinion on the result.
Or ask your AI tool to do it
Paste this into Lovable, Bolt, Cursor, Claude Code or whichever tool built your app. Review what it changes before you deploy.
My app is a React single-page app built with Vite. Add a Content Security Policy. First run the production build and list every <script> in dist/index.html: external files, inline scripts and inline event handlers (onclick= etc.). Move inline scripts into modules under src/ and replace inline event handlers with addEventListener. Then write a policy starting from: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'. Add every external domain the app really uses: my Supabase project URL (https:// and, only if I use Realtime, wss://) and other API addresses to connect-src, third-party scripts to script-src, Stripe.js sources from Stripe's CSP docs if I use Stripe Elements. Never add data: or 'unsafe-inline' or 'unsafe-eval' to script-src. Add the policy to preview.headers in vite.config.js as Content-Security-Policy-Report-Only so I can test it with vite preview, and add the same header to my host's config (Netlify _headers in public/, or vercel.json). List each external domain you added and why, so I can review it before switching the header to Content-Security-Policy.
How this happens
Nothing breaks without a CSP, so nobody adds one. Lovable, Bolt and similar builders generate the app, not the hosting config, and their previews run on their own servers. When the app moves to Netlify, Vercel or a custom domain, the header simply isn't there. It shows up as a problem only when someone runs a scanner or a customer's security review asks for it, and then it looks scary because a wrong policy can break the app. Report-only mode is what makes it safe to try.
Check that it's really fixed
After you deploy, run the free check. It reads your live site the way an attacker would and tells you if any secret key is still visible.
Topic check: Security headers check
Find the other leaks before someone else does
The free check reads your home page and its scripts. The website security report goes through up to 30 pages and 40 JavaScript files, plus .env and .git files, security headers, cookies and CORS, domain and email records, and libraries with known vulnerabilities. Every finding comes with the fix for your host and a prompt for your AI tool.
$19 once, including 20 runs over 30 days so you can fix things and check again.

Questions
Does a React app need 'unsafe-inline' in script-src?
A React app built with Vite usually doesn't: its production build loads your code from script files, which script-src 'self' allows. You'd need more only for inline scripts you or a tool added to index.html, and those are better moved into a file or allowed by hash. Next.js is different because it adds inline scripts to every page; see our Vercel guide for its CSP.
Why does the policy allow data: for images and fonts?
Vite's docs say a production build inlines small assets (images, fonts) as data: URIs, so img-src and font-src need data:. You can set build.assetsInlineLimit: 0 to stop the inlining instead. Don't allow data: in script-src: Vite's docs warn it lets attackers inject scripts.
Can I put the CSP in a meta tag in index.html?
Only as a fallback. MDN says a meta tag doesn't support every CSP feature: report-only policies can't be delivered that way and frame-ancestors is ignored. Use a response header from your host, so you can start in report-only mode and also block framing.
What does Supabase need in the CSP?
Your project URL, https://YOUR-PROJECT.supabase.co, in connect-src, because the Supabase client calls it for data, auth and storage. If you use Realtime, add wss://YOUR-PROJECT.supabase.co too; Supabase's Realtime protocol docs show it connects over a WebSocket on that host. A CSP doesn't protect your database: anyone can still call the Supabase API directly, so Row Level Security is what keeps data safe.
Will a Content Security Policy stop all XSS?
No. Google's web.dev calls it defense in depth: it makes an injected script much harder to run, but you still need to escape and sanitize what users enter. A strict, nonce-based policy is stronger than a list of allowed domains; MDN notes that allowlist policies often end up allowing unsafe domains by accident.
Why does your free check still say "No Content Security Policy"?
The free check only counts an enforcing Content-Security-Policy header, so a report-only policy still shows up until you switch it on. The $19 report grades the policy itself (report-only, 'unsafe-inline', 'unsafe-eval', wildcard script sources) and drafts a starting CSP from what your pages actually load: the API, auth and analytics endpoints in your code, third-party scripts, styles, fonts and frames, and hashes for your inline scripts, with the reason for each source and the config for your host.
Sources
- Vite: Content Security Policy (nonce, data: URIs)
- Vite: Preview options (preview.headers)
- MDN: Content Security Policy (CSP) guide
- MDN: Content-Security-Policy-Report-Only
- MDN: CSP frame-ancestors (not supported in meta)
- MDN: CSP style-src
- web.dev: Mitigate cross-site scripting (XSS) with a strict CSP
- Chrome for Developers: CSP issues in DevTools
- Supabase: Realtime protocol (WebSocket URL)
- Stripe: Integration security guide (Content Security Policy)
- MUI: Content Security Policy
- Netlify: Content Security Policy (nonce extension)
- Google: CSP Evaluator