Configuring Content Security Policy (Part 6): CSP with React, Vue, Next.js, Angular, Vite and Astro
Make a strict CSP work with modern frontend frameworks and build tools. Covers SSR vs static rendering, nonces, Vite CSP placeholders, Angular CSP support, Next.js dynamic rendering and Astro CSP.

A Content Security Policy that looks straightforward on a hand-written HTML page can become much more interesting once a modern framework enters the picture.
React, Vue, Angular, Next.js, Nuxt, Vite and Astro all generate or transform browser resources on your behalf. Framework runtimes inject scripts. Bundlers create module-preload tags. CSS-in-JS libraries create style elements. Server-rendered frameworks hydrate pages with inline bootstrapping data. Development servers may rely on eval() or WebSockets. Static-site generators may hash or inline assets at build time.
None of this means modern frameworks are incompatible with CSP.
It means you need to design the policy around what the production build actually emits, not around the source files you remember writing.
This guide shows how to do that without weakening the policy until the console becomes quiet.
The first rule: test the production build
Development mode is deliberately unusual.
A dev server may use:
- hot module replacement;
- WebSockets;
- source-map helpers;
- runtime code generation;
- injected client scripts;
- inline styles;
eval()for debugging;- additional localhost origins.
A production build may use none of those things.
If you design your production CSP around npm run dev, you can easily end up adding permissions that production never needed.
A safer workflow is:
Developer CSP
│
├── permits the minimum needed for local tooling
│
▼
Production build
│
├── inspect generated HTML/assets
├── run locally as production
└── derive production CSP from this output
Keep development exceptions explicit rather than silently carrying them into production.
React itself is not the CSP problem
A normal client-side React bundle served from your own origin can work with a straightforward script policy:
script-src 'self'
The complications usually come from the surrounding architecture:
- server rendering;
- framework bootstrapping scripts;
- CSS-in-JS;
- third-party scripts;
- development tooling;
- code that writes raw HTML;
- libraries that require
eval(); - WebAssembly;
- dynamic chunk loading.
React’s JSX escaping also does not replace CSP. dangerouslySetInnerHTML, direct DOM manipulation and third-party libraries can still create DOM XSS sinks if untrusted data reaches them unsafely.
Treat React’s built-in escaping and CSP as complementary controls.
Next.js: nonces have a real rendering cost
Next.js has unusually good current CSP documentation because nonce-based CSP affects its rendering model directly.
For a nonce policy, a request might carry:
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{NONCE}' 'strict-dynamic';
style-src 'self' 'nonce-{NONCE}';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none'
Next.js can extract the nonce during dynamic rendering and apply it to framework scripts and other generated resources.
But there is a major consequence:
nonce-based CSP requires per-request dynamic rendering.
A nonce does not exist at static build time because it must be new for every response.
Current Next.js guidance therefore notes that nonce-based CSP disables the normal advantages of static rendering for affected pages, including static optimisation and straightforward CDN caching. Partial Prerendering is also incompatible with the nonce model because a static shell cannot know a future request’s nonce.
That is not a small implementation detail.
It is an architecture decision.
Next.js: choose nonce security with your eyes open
A nonce-based Next.js application can be an excellent choice when:
- the application is already dynamic;
- pages contain sensitive authenticated data;
- strict CSP is a strong requirement;
- the server or edge layer can generate a fresh nonce per request;
- the loss of static caching is acceptable.
It may be a poor fit when:
- the site is mostly static marketing content;
- CDN caching is a major performance/cost strategy;
- every page can already be built deterministically;
- hash-based CSP or external scripts can provide equivalent protection more naturally.
Do not make an entire static site dynamically rendered solely because nonce examples are easier to copy.
Next.js development and 'unsafe-eval'
Current Next.js documentation explicitly distinguishes development from production.
Development uses eval() in some debugging paths, so a development policy may need:
'unsafe-eval'
The production runtime does not require that permission by default.
That gives us a very practical rule:
Development needs unsafe-eval?
│
└── fine, if documented and local only
Production policy contains unsafe-eval?
│
└── investigate exactly which dependency requires it
Never copy a development CSP into production unchanged.
Next.js third-party components still need the nonce
If you deliberately include a third-party script using Next’s script helpers, pass the nonce through the supported component path rather than falling back to inline exemptions.
Conceptually:
<Script
src="https://vendor.example/widget.js"
nonce={nonce}
/>
The same principle applies to framework integrations that expose nonce support: use the framework’s intended mechanism so generated HTML remains consistent with the response header.
Vue: focus on the build tool and your own DOM behaviour
Vue applications themselves are generally straightforward under CSP when templates are precompiled and scripts/styles are emitted as external assets.
The issues tend to come from:
- Vite output;
- runtime template compilation;
- raw HTML through
v-html; - CSS-in-JS or component libraries injecting styles;
- third-party widgets;
- dynamic URLs/resources.
For example:
<div v-html="userSuppliedHtml"></div>
is not made safe merely because Vue is present.
If the HTML is untrusted, sanitise it appropriately. CSP then provides another layer of defence.
Avoid constructing templates from untrusted strings at runtime.
Vite has explicit CSP nonce support
Current Vite exposes an html.cspNonce setting.
When configured, Vite applies the supplied nonce placeholder to generated script/style tags and relevant stylesheet/module-preload links, and emits a csp-nonce meta marker that Vite can use when it needs the nonce.
Conceptually:
export default defineConfig({
html: {
cspNonce: '__CSP_NONCE__'
}
})
The critical word is placeholder.
Vite’s documentation warns that the placeholder must be replaced with a unique value for each request when using a nonce-based policy.
Shipping the same built nonce to everybody defeats the one-time property.
Vite and static hosting: think before choosing a nonce
A pure Vite SPA is often compiled into static files and served from a CDN.
If index.html is immutable and shared by all visitors, a per-response nonce requires an edge/server transformation layer.
You have several options:
Static Vite SPA
│
├── avoid inline script + use source-based/hash strategy
├── generate hashes at build time
├── transform nonce placeholder at edge per response
└── move to dynamic HTML if justified
Do not put a fixed nonce in vite.config and call the problem solved.
Vite may inline small assets as data: URLs
Vite can inline small assets as data URIs during production builds.
That may require directives such as:
img-src 'self' data:
or:
font-src 'self' data:
depending on what the build emits.
Vite’s documentation explicitly warns not to allow data: in script-src, because that would enable arbitrary script injection through data URLs.
If you do not want data: resources at all, configure the bundler not to inline them rather than broadly relaxing CSP.
Angular has first-class nonce support
Angular’s current security documentation provides several supported CSP approaches.
A minimal new Angular application policy is documented along these lines:
default-src 'self';
style-src 'self' 'nonce-{NONCE}';
script-src 'self' 'nonce-{NONCE}'
Angular needs the nonce so framework-generated <style> elements and applicable scripts can be authorised.
Current Angular supports multiple ways to supply it, including:
- automatic CSP tooling (
autoCsp); - an
ngCspNonceattribute on the root application element; - the
CSP_NONCEinjection token.
That is much better than injecting 'unsafe-inline' just because Angular rendered a style element.
Angular and CDN-cached HTML
Angular’s own documentation highlights a subtle nonce issue that applies to any framework:
if the origin inserts a nonce and a CDN caches that HTML, subsequent users may all receive the same supposedly one-time nonce.
That breaks the security assumption.
Where HTML is cached, generate the nonce at the edge immediately before delivery, or use an architecture that does not depend on per-response nonce mutation.
Caching and nonce generation must be designed together.
Angular’s sanitisation is valuable — and still not enough by itself
Angular treats template-bound values as untrusted and sanitises according to security context.
That significantly reduces common XSS mistakes.
But direct DOM APIs, third-party libraries and bypass APIs can escape that safety model.
Methods such as the bypassSecurityTrust... family should receive the same scrutiny as dangerouslySetInnerHTML in React or v-html in Vue.
A strict CSP and Trusted Types strengthen the browser boundary even if framework-level sanitisation is bypassed accidentally.
We will cover Trusted Types in Part 8.
Astro 6 now has built-in CSP support
This is an important freshness point for 2026.
Astro 6 promotes CSP support to a stable security.csp configuration feature.
That can handle Astro’s processed and bundled scripts/styles and generate CSP output based on the build.
For a static-content framework, this is attractive because hash-based CSP often fits naturally with deterministic build output.
Conceptually:
export default defineConfig({
security: {
csp: true
}
})
Do not assume enabling it solves every resource in your application. Astro’s documentation notes limitations, including external scripts/styles requiring explicit handling such as custom hashes/configuration.
Third-party integrations still need deliberate trust decisions.
Inspect what your framework actually ships
A framework config can look correct while the final CDN response differs. Use SiteTidy alongside browser testing to verify the CSP and wider security-header posture users actually receive.
Static Astro sites are excellent candidates for hashes
A statically generated page has an advantage: its inline script/style bytes are known at build time.
That means the build can calculate hashes and emit a policy that authorises exactly those bytes.
No per-request HTML mutation is required.
This preserves:
- full CDN cacheability;
- static hosting;
- deterministic CSP;
- narrow script trust.
If an integration changes the final bytes after CSP generation — perhaps through another deployment transform — the hash stops matching. Calculate policy from the final representation.
Nuxt: distinguish SSR from static generation
The same architectural decision applies to Nuxt even though implementation details vary by version/module setup.
For SSR:
request
-> generate nonce
-> attach CSP
-> render trusted script/style elements with nonce
For prerendered/static output:
build
-> know final script/style content
-> externalise or hash
-> deploy deterministic CSP
Do not force nonce-based dynamic rendering onto a prerendered site unless the threat model justifies that trade-off.
Check the exact Nuxt/Nitro version and deployment adapter before copying CSP examples because response-header and rendering APIs evolve.
CSS-in-JS deserves its own inventory
Libraries such as styled-components, Emotion and other runtime styling systems may inject <style> elements dynamically.
A strict:
style-src 'self'
can therefore break an otherwise functioning application.
Before reaching for:
style-src 'self' 'unsafe-inline'
check whether the library supports:
- nonce propagation;
- server-extracted styles;
- build-time CSS extraction;
- an official CSP integration.
Runtime styling is a legitimate application behaviour, but it should be authorised intentionally.
Hydration data can look like executable code
SSR frameworks need to transfer server state to the browser.
You may see inline blocks such as:
<script type="application/json" id="__APP_STATE__">
{"user":{"name":"Neil"}}
</script>
or framework-specific bootstrapping script tags.
Not every <script> contains executable JavaScript; MIME type and framework handling matter.
Nevertheless, inspect what your framework emits and what CSP directive applies. Avoid inventing broad inline permissions based on the tag name alone.
Also make sure serialised state safely escapes values that could prematurely close a script element or otherwise create markup injection.
Dynamic imports and code splitting
Modern bundlers create multiple JavaScript chunks and load them on demand.
Under an ordinary same-origin policy:
script-src 'self'
same-origin chunks are usually straightforward.
Under a strict nonce + strict-dynamic policy, dynamically loaded scripts/chunks need to follow the trusted execution model supported by the framework/bundler.
Do not hard-code today’s generated chunk filenames into CSP. Fingerprints change on every build.
Trust the controlled loading mechanism, not individual ephemeral asset names.
Module preload links are worth testing
Build systems may emit:
<link rel="modulepreload" href="/assets/chunk-abc.js">
or stylesheet preload links.
The browser’s CSP checks for preload/module resources can expose surprising configuration gaps.
Vite’s nonce support deliberately includes relevant module-preload and stylesheet links for this reason.
Test a production build with DevTools open rather than verifying only that the main bundle has a nonce.
WebAssembly and wasm-unsafe-eval
Applications using WebAssembly may encounter CSP errors even when ordinary JavaScript is properly authorised.
CSP provides the 'wasm-unsafe-eval' source expression to control WebAssembly compilation in supporting browsers without granting the broader JavaScript string-evaluation capability of 'unsafe-eval'.
If your app genuinely uses WASM, prefer the narrower permission where compatible:
script-src 'self' 'wasm-unsafe-eval'
rather than automatically adding:
'unsafe-eval'
Next.js documentation explicitly calls out this distinction in CSP troubleshooting.
Service Workers need deliberate testing
A PWA may register:
navigator.serviceWorker.register('/sw.js');
Worker loading is governed by worker-src, with fallback behaviour if that directive is absent.
A sensible policy may include:
worker-src 'self'
If a framework/build tool generates workers via blob URLs, you may need:
worker-src 'self' blob:
Only permit blob: when you have identified the exact feature requiring it.
Service Workers also persist beyond the current page, so stale workers can complicate CSP rollout testing. Test clean and upgraded clients.
Hot Module Replacement is not production behaviour
Vite and other dev servers use WebSockets for HMR.
Your development policy may therefore need something like:
connect-src 'self' ws://localhost:5173
That does not mean production needs arbitrary WebSocket permission.
Keep local origins out of production headers.
If the application itself uses WebSockets in production, authorise the real wss:// endpoint separately.
Inline environment configuration is often avoidable
A common deployment pattern writes configuration into an inline script:
<script>
window.__CONFIG__ = {
apiBase: 'https://api.example.com'
};
</script>
That can work with a nonce/hash, but it creates CSP plumbing.
Alternatives include:
- a JSON endpoint;
- a non-executable JSON script block consumed safely;
- server-rendered data attributes;
- framework runtime configuration mechanisms;
- external generated config files.
Do not add 'unsafe-inline' for one small configuration object.
Avoid runtime template compilers in production where possible
Frameworks that support runtime compilation from template strings may need code-generation capabilities or expand the XSS surface.
Use production builds with precompiled templates/components where your framework supports them.
For Angular, current guidance specifically recommends AOT compilation in production.
For Vue and similar ecosystems, prefer compiler-free runtime builds when you do not need client-side template compilation.
Build-time compilation is easier to secure and easier to reason about under CSP.
Framework escape hatches deserve a security code review
Every major framework offers ways to say “I know this value is safe.”
Examples include:
React -> dangerouslySetInnerHTML
Vue -> v-html
Angular -> bypassSecurityTrust...
DOM -> innerHTML / insertAdjacentHTML
These APIs are not automatically vulnerabilities.
They are trust decisions.
When you see them, ask:
- where did the value come from?
- is it sanitised?
- which sanitizer/policy is used?
- can an attacker influence it?
- can Trusted Types enforce the boundary centrally?
CSP is much stronger when the application does not deliberately create dangerous sinks everywhere.
A practical framework CSP workflow
Instead of searching for “best CSP for React” and pasting the first result, use this process:
1. Build production output
2. Run it in production mode
3. Inventory scripts/styles/network/frame/worker behaviour
4. Identify framework-generated inline content
5. Check official framework/bundler CSP support
6. Decide nonce vs hash based on rendering architecture
7. Remove development-only permissions
8. Add third-party integrations deliberately
9. Test in Report-Only
10. Run critical browser journeys under enforcement
That workflow remains valid even as framework versions change.
Do not fight the framework blindly
If a framework has first-class nonce/hash/CSP support, use it. Hand-patching generated HTML after the build is fragile and can accidentally authorise content the framework never intended to trust.
Browse SiteTidy's security toolsFramework-specific checklist
Before enforcing CSP on a modern frontend, verify:
[ ] Production build tested, not only dev server
[ ] Dev-only unsafe-eval/localhost/WebSocket permissions removed
[ ] SSR/static rendering strategy understood
[ ] Per-response nonce caching implications understood
[ ] Framework-generated scripts receive nonce/hash correctly
[ ] Runtime-injected styles handled deliberately
[ ] Dynamic imports/code splitting tested
[ ] Modulepreload/preload resources tested
[ ] Service Workers/workers tested
[ ] WASM policy added only if used
[ ] Third-party framework plugins inventoried
[ ] Raw HTML / trust-bypass APIs reviewed
[ ] Final public CSP verified after CDN/proxy
If all of those are explicit, framework CSP stops feeling mysterious.
Final thought
There is no universal “React CSP”, “Vue CSP” or “Next.js CSP”.
There is an application’s browser behaviour, produced through a particular framework and deployment architecture.
The right policy follows that behaviour while preserving a strong trust model.
Sometimes that means a per-response nonce. Sometimes it means build-time hashes. Sometimes it means removing a runtime styling library. Sometimes it means keeping a static site static instead of forcing dynamic rendering for the sake of a nonce.
The framework is an implementation constraint, not an excuse to add 'unsafe-inline' and 'unsafe-eval' permanently.
In Part 7, we will step outside scripts and styles and cover the awkward resource types that usually cause the last round of CSP breakage: frames, workers, forms, WebSockets, blob:, data:, media and mixed-content behaviour.
