Most Astro websites are fast by default, but performance does not automatically mean that every browser resource is trustworthy. A compromised dependency, an injected script, or an unexpected third-party resource may still put visitors at risk.
A Content Security Policy (CSP) adds a browser-enforced set of restrictions on where scripts, styles, images, frames, and network requests may originate. For a static Astro site deployed to Cloudflare Pages, you can start with a response header in public/_headers, observe what would be blocked, and tighten the policy gradually.
This guide walks through a cautious implementation that accounts for real integrations—including analytics, Cloudflare Turnstile, Decap CMS, and Pages Functions—without pretending that one universal CSP works for every website.
Scope: These are configuration examples for a static Astro site. They have not been executed against your repository. Test them on a preview deployment, inventory actual resource origins, and never copy a restrictive example straight into production.
1. What Is a Content Security Policy?
CSP is an HTTP response policy interpreted by the browser. It limits which resources a page is permitted to use and can reduce the impact of several injection attacks.
For example, a page might need JavaScript from its own domain but no executable code from unknown domains. A CSP can express that policy through the script-src directive.
However, CSP is a defense-in-depth control, not a substitute for escaping user input, dependency maintenance, secure authentication, or server-side validation. An incorrect CSP can also break legitimate functions.

Figure 1. The browser evaluates requested resources against the page’s CSP and allows or blocks them according to the configured directives.
2. Understand the Most Useful CSP Directives
| Directive | Purpose | Typical starting idea |
|---|---|---|
default-src |
Fallback for many resource categories | 'self' |
script-src |
JavaScript sources and execution rules | Explicit trusted sources, hashes or nonces |
style-src |
CSS and inline style policies | First-party CSS, then review inline styles |
img-src |
Images and image data | 'self' plus required image origins |
font-src |
Font loading | 'self' plus required font service |
connect-src |
Fetch, XHR, WebSocket, Beacon endpoints | First-party and necessary API hosts |
frame-src |
Frames loaded by this page | Turnstile or other necessary origins |
frame-ancestors |
Which pages may embed this page | 'none' or approved parent origins |
object-src |
Legacy plug-in content | 'none' |
base-uri |
Permitted HTML <base> values |
'self' or 'none' |
form-action |
Where HTML forms may submit | 'self' plus deliberate exceptions |
Important details: frame-ancestors and form-action do not simply inherit from default-src. Set them explicitly when you need their protections. Source lists are contextual; adding an entire domain may permit more resources than intended.
3. Inspect Your Current Astro Website First
Before adding a policy, open the main pages of your site in browser DevTools and review the Network tab:
- Homepage and an ordinary blog post.
- Pagefind search and its search index files.
- Contact form, if enabled, including Turnstile verification.
- Analytics only after a visitor grants consent, if the site follows that design.
- The Decap CMS admin interface and authentication redirects.
- Any third-party embeds, fonts, and media.
Make a short inventory of actual resource types and their origins. Avoid guessing domains based only on what libraries you installed. A page might send requests to a different API origin than the script it downloaded.
Privacy note: Do not turn on analytics without consent merely because your CSP diagnostics fail to detect Google tags. CSP and consent management are separate concerns.
4. Understand How Cloudflare Pages Applies _headers
For a static Astro project, create this file in the source repository:
public/_headers
Astro normally copies the public/ directory into the built output. Cloudflare Pages reads _headers and attaches matching headers to static asset responses.
A basic file looks like this:
/*
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
After your build, verify the file actually exists at dist/_headers (or your configured output directory).
Critical distinction: Cloudflare says these _headers rules do not automatically apply to responses generated by Pages Functions. For endpoints implemented using Functions, set headers on the returned Response object instead.
Also note that Cloudflare has limits on rule count and line length. Keep long CSP policies readable in your source configuration, but the final HTTP header value must be formatted as a valid single policy value.
Official source: Cloudflare Pages — Headers.
5. Start with Report-Only, Not Enforcement
A first CSP often discovers inline scripts, dynamically injected styles, third-party APIs, or embedded frames that a simple policy does not account for.
Deploy this illustrative trial policy to a preview branch, modifying the sources for your project:
/*
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
The Report-Only header means the browser can report violations without enforcing this particular policy. Open DevTools → Console and check for CSP warnings while using the site.
Do not interpret the absence of console messages in one short test as evidence that everything is compatible. Test multiple routes, fresh sessions, consent states, and relevant user interactions.
A report-only header does not automatically send violations to a server unless you configure a reporting destination. In an early manual audit, the browser console may be enough. For sustained monitoring, design a protected reporting endpoint and review the privacy and noise implications.
6. Avoid Breaking Inline Astro Scripts and Styles
The previous trial policy may flag inline scripts or styles emitted by your site or integrations. This is expected and useful information.
Options for reducing the violations include:
- Move custom inline JavaScript to external modules where practical.
- Use CSP hashes for stable inline code in static HTML.
- Use per-response nonces for dynamically generated HTML that can securely inject a new random nonce on every response.
- Revisit third-party tools that require broad unsafe permissions.
For a static Astro build, a fixed nonce embedded into every page is not a safe substitute for a true per-response nonce. Hash-based authorization is often more appropriate for static output, though the hash needs rebuilding whenever the inline code changes.
Do not add 'unsafe-inline' or 'unsafe-eval' globally simply to silence console errors. Broad exceptions weaken the protections that CSP is supposed to provide.
Consult MDN’s CSP implementation guide before implementing a strict hash-based or nonce-based policy.
7. Make Cloudflare Turnstile Compatible
A contact page that uses Cloudflare Turnstile needs access to Cloudflare’s challenge resources.
Cloudflare documents these allowances as an alternative to a nonce-based setup:
script-src 'self' https://challenges.cloudflare.com;
frame-src 'self' https://challenges.cloudflare.com;
These two lines are directive fragments, not a complete policy. Integrate them into your actual script-src and frame-src directives rather than adding duplicate directives.
If the widget uses Turnstile pre-clearance, Cloudflare also notes that its request to /cdn-cgi/ requires an appropriate connect-src, including 'self' for a same-origin request.
Remember that CSP only controls which resources the browser may load. Turnstile still requires server-side Siteverify and normal abuse controls; allowing its script in CSP does not validate submissions.
Official source: Cloudflare Turnstile — Content Security Policy.
8. Make Google Analytics Work Without Bypassing Consent
If your Astro site loads GA4 only when a visitor grants analytics consent, the CSP should accommodate the legitimate script and network requests after consent, not force analytics to run before consent.
Potential resources include Google tag scripts and Google Analytics collection endpoints. Their exact hosts depend on your tagging setup, region and configuration, so identify them in DevTools after a controlled opt-in test.
Check both script-src and connect-src. Allowing a tag script but blocking its outgoing collection requests can create a misleading partial integration.
Test two separate states:
- Before consent: your site’s consent policy prevents analytics from loading or sending data, as intended.
- After consent: GA4 loads, requests comply with CSP, and the expected
page_viewreaches GA4 Realtime or Tag Assistant.
Do not treat “Google Tag not detected” before consent as a reason to disable privacy controls.
9. Test the Decap CMS Admin Route Independently
A site with Decap CMS, OAuth redirects and the editorial workflow has additional requirements. The /admin/ area may load JavaScript bundles, use popup authentication, communicate with GitHub or an auth worker, and require frame or network permissions different from your public blog.
A policy that works on /blog/ can break /admin/.
On a preview deployment, test:
- Sign in and return from the OAuth flow.
- Load the CMS editor and existing posts.
- Save a draft, preview Markdown and upload an image.
- Publish and confirm the Git-based editorial workflow still functions.
Where necessary, assign a deliberate, route-specific CSP instead of weakening the public site’s policy everywhere. Check how multiple matching _headers rules combine; do not assume a more specific rule replaces a less specific CSP header. If two separate CSP policies reach a browser, their restrictions can both apply.
This guide does not invent a universal allowlist for Decap CMS. Determine required origins from the specific deployed configuration.
10. Build a Safe Rollout Plan
The safest production process is gradual:
- Inventory first-party and third-party browser resources.
- Deploy
Content-Security-Policy-Report-Onlyto a preview branch. - Exercise critical features and record legitimate violations.
- Remove unnecessary inline code and narrow any needed exceptions.
- Run tests on public pages, Contact, GA4 opt-in, search and Decap CMS.
- Switch to enforcement only after acceptable coverage.
- Monitor future content and dependency changes for new violations.

Figure 2. Audit existing resources, test in report-only mode, repair legitimate violations and enable enforcement only after verification.
11. Apply an Enforced Policy Only After Testing
Once your preview checks pass, replace your tested Content-Security-Policy-Report-Only header with an enforcing Content-Security-Policy header.
Example baseline for a deliberately minimal, static page with no inline scripts or external dependencies:
/*
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
This is not a drop-in production policy for a site running Decap CMS, Turnstile, GA4 or embedded media. It may break those features. Use your verified, route-appropriate source lists and script authorization approach instead.
The security value comes from matching a restrictive policy to a functioning site—not from copying a seemingly strict string.
12. Pages Functions Need Their Own Headers
If a route is generated by Cloudflare Pages Functions, configure CSP and related security headers in that Function or an appropriate shared middleware layer.
A minimal TypeScript example of modifying a response:
export const onRequestGet: PagesFunction = async (context) => {
const response = await context.next();
const headers = new Headers(response.headers);
headers.set('X-Content-Type-Options', 'nosniff');
headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
// Only apply a page CSP after testing its actual requirements.
// API JSON endpoints do not need the same resource policy
// as interactive HTML pages.
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
};
This example focuses on response-header handling and is not a ready-made route setup. PagesFunction types and context.next() require the relevant Pages Functions environment and route structure. Do not place this handler in a route without checking whether that route already has a handler or middleware.
A JSON API endpoint might need other headers, such as restrictive CORS and cache controls, but it does not necessarily benefit from receiving the same browser document CSP as a rendered page.
13. Verify Response Headers After Deployment
Do not stop after committing public/_headers.
Build locally:
npm.cmd run build
Test-Path .\dist\_headers
Then inspect the deployed document response:
curl.exe -I https://example.com/
Look for the exact Content-Security-Policy-Report-Only or Content-Security-Policy response header you intended to deploy. Replace example.com with your domain.
Next test the browser’s Network and Console tabs. Verify the header on public blog pages, the Contact page, and any other affected route. Test after an actual deployment: _headers applies on Cloudflare Pages, not merely because a file exists in your source repository.
Also check whether another proxy, Worker or middleware inserts an additional CSP policy. Multiple policies can restrict resources more than expected.
14. Diagnose Common CSP Errors
| Symptom | Likely cause | Next step |
|---|---|---|
| Inline script blocked | No matching hash or nonce | Move it to a trusted external module or authorize appropriately |
| Turnstile not visible | Challenge script or frame disallowed | Check script-src and frame-src |
| GA4 tag loads but no data | Collection endpoint blocked or consent denied | Verify connect-src and consent state |
| CMS login fails | Auth redirect or network calls restricted | Trace /admin/ resources and exact hosts |
| Images or fonts disappear | img-src or font-src too narrow |
Add only observed necessary origins |
_headers change seems ignored |
Response generated by Function, or deploy mismatch | Inspect actual response headers and route |
| Everything works only in Report-Only | Violations would be enforced in active mode | Fix legitimate violations before switching |
Avoid resolving all issues with * or 'unsafe-inline'. Each exception should have a documented business need.
15. Security Checklist Before Production
- Audited resource origins on key page types.
- Verified
_headersis included in the output directory. - Tested CSP in Report-Only mode.
- Documented legitimate inline scripts and styles.
- Verified Turnstile’s script and frame requirements.
- Tested analytics before and after opt-in.
- Tested Decap CMS login, draft save and image upload.
- Checked Pagefind search and page navigation.
- Verified Pages Functions responses separately.
- Checked actual HTTP response headers.
- Rejected overly broad exceptions where possible.
- Tested rollback on a preview deployment.

Figure 3. Inspect static pages, Functions, Turnstile, consent-dependent analytics and the CMS editor separately before enforcing CSP.
16. Frequently Asked Questions
Does Astro automatically protect every page with CSP?
No. Astro’s static generation does not mean that your deployed responses automatically use the CSP you need. Audit the actual headers and emitted HTML for your version and hosting configuration.
Can CSP improve SEO or PageSpeed scores?
CSP is primarily a browser security control. It should not be presented as a guaranteed SEO ranking factor or a way to increase Lighthouse Performance. Its configuration can affect resource loading, so test for regressions.
Should I use a nonce or a hash on static Astro pages?
For static HTML, a hash-based approach is often practical for stable inline code. A secure nonce must be unpredictable and newly generated per response, normally requiring dynamic response handling.
Can I use CSP with Cloudflare Turnstile?
Yes. Follow Cloudflare’s documented script and frame allowances or an appropriate nonce-based configuration, and keep server-side verification enabled.
Why did CSP break my Decap CMS editor?
The editor may load external code or make authenticated network requests that your policy blocks. Audit the admin route separately and permit only the necessary sources.
Does public/_headers protect Pages Functions endpoints?
Not automatically. Cloudflare Pages documents that Functions-generated responses require explicit header handling within Functions or middleware.
17. Final Thoughts
An effective Content Security Policy is not a one-line security trick. It is a documented browser resource policy that should evolve with your website.
For Astro on Cloudflare Pages, the practical path is straightforward: inventory resources, add a report-only header, examine real violations, test your integrations, and enforce a carefully reviewed policy. Treat dynamic Functions responses as a separate case.
The goal is to reduce the damage untrusted code can cause without breaking legitimate visitor experiences.
Continue Reading
- Astro SEO Guide 2026: 12 Essential Steps to Optimize Your Website for Google — Review the broader technical SEO foundation of an Astro blog.
- How to Add Google Analytics 4 Consent Mode to Astro (2026 Guide) — Keep analytics dependent on visitor consent.
- How to Build a Secure Contact Form in Astro with Cloudflare Turnstile and Pages Functions (2026 Guide) — Understand Turnstile’s server-side role and Pages Functions.
Official References
- Cloudflare Pages — Custom Headers
- Cloudflare Turnstile — CSP
- MDN — CSP Implementation Guide
- MDN — Content Security Policy
- Cloudflare — CSP and Cloudflare
Technical disclosure: Examples are educational and have not been tested against a specific production repository. CSP requirements depend on the site’s emitted assets, scripts, routes, and integrations. Always validate on a preview deployment before enforcement.






