A single console error dropped a real Astro site's Lighthouse Best Practices score from 100 to 92. The site's own code wasn't the cause. Cloudflare's auto-injected analytics beacon broke a strict script-src 'self' policy. This guide walks through the setup that avoids that, and how to prove it worked.
Every code sample here is unexecuted. Nothing below was run for this article, so treat the build output as an illustration of what to look for, not captured logs.
What you are fighting
Two things break script-src 'self' without unsafe-inline.
The first is your bundler. According to the write-up of an Astro roof calculator that scores 100 on Lighthouse, Vite inlines small scripts into the HTML by default, and a strict CSP blocks them. An inlined script has no URL, so 'self' cannot match it.
The second is your host. The same write-up reports that Cloudflare's Web Analytics injected a beacon script into every page. The CSP blocked it, and the console error dropped Best Practices from 100 to 92. Turning off the automatic injection brought the score back to 100.
Your Astro version may already handle some of this. The write-up doesn't say, and Astro's behavior can change between releases. Before copying anything below, check the current Astro docs for built-in CSP support and for how inline scripts are handled in the version you run. If a built-in option exists, it may replace parts of this setup.
Step 1: Pin your versions
The write-up doesn't state which Astro, Vite or Node versions it used, so no exact numbers are asserted here. Record your own:
npm ls astro vite
node --version
Then pin them in package.json, so the build you verify is the build you ship:
{
"scripts": { "build": "astro build", "preview": "astro preview" },
"dependencies": { "astro": "<exact version from npm ls>" }
}
Replace the placeholder with the version your own machine reports. No lockfile result is claimed here.
Step 2: Force scripts into separate files
Set assetsInlineLimit to 0 so Vite never inlines a small asset. The write-up uses this setting:
// astro.config.mjs (unexecuted)
import { defineConfig } from 'astro/config';
export default defineConfig({
output: 'static',
vite: {
build: { assetsInlineLimit: 0 }, // never inline scripts (CSP)
},
});
``` We cover related ground in [see also: sharp vs cloudinary vs imgix for fixed avatar sizes](/sharp-vs-cloudinary-vs-imgix-for-fixed-avatar-sizes).
The mechanism is a size threshold. Vite compares each asset to `assetsInlineLimit` and inlines anything under it. At 0, nothing qualifies. Every script becomes its own file served from your origin, which is exactly what `'self'` allows.
Now add a deliberately tiny script, small enough to be a classic inlining candidate:
// src/scripts/hello.ts (unexecuted) const el = document.querySelector('#out'); if (el) el.textContent = 'Loaded from an external file';
// src/pages/index.astro (unexecuted)
<html lang="en"> <head><meta charset="utf-8" /><title>CSP test</title></head> <body> <p id="out">Waiting for script</p> <script>import '../scripts/hello.ts';</script> </body> </html> ```Don't put the is:inline directive on script tags. It tells Astro to leave the script in the HTML as written, which defeats the point.
Step 3: Set the policy in a _headers file
Cloudflare Pages reads a _headers file from your build output. Put it in public/ so Astro copies it to dist/ untouched:
## public/_headers (unexecuted)
/*
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
X-Content-Type-Options: nosniff
There is no unsafe-inline anywhere. One catch: default-src 'self' also covers styles, and script-src does not. If your build puts CSS into <style> tags, a policy like this will block them. The write-up sets inlineStylesheets: 'always', and Astro's default can inline small stylesheets too. The write-up doesn't say how its style-src was written. Either let Astro emit CSS as files, or add a separate style-src on purpose. Don't widen script-src to fix a style problem.
If the site is live, run the policy in report-only mode first. Swap the header name for Content-Security-Policy-Report-Only, check the console, then switch back. For more on this, see a closer look at rds inaccessible encryption credentials: kms triage guide.
Step 4: Deal with Cloudflare Web Analytics
Automatic injection adds a script your build never saw. The policy says scripts must come from your own origin, so the browser refuses it and logs a violation. Lighthouse counts console errors under Best Practices, which is how a clean site loses points.
You have two options:
- Turn off automatic injection for the site in the Cloudflare dashboard. The write-up's author did this, and the score returned to 100.
- Keep analytics and allow the beacon explicitly. Add its script host to
script-srcand its reporting endpoint toconnect-src. Cloudflare's documentation lists the exact hosts; they aren't in the write-up, so none are named here. This also meansscript-srcis no longer just'self'.
For a small site where the goal is a locked-down policy, option 1 is simpler. Choose option 2 only if you need the numbers.
Step 5: Build and check the output
npm run build
ls dist dist/_astro
Expect something shaped like this. The names and hashes are illustrative, not real output:
Also read: also worth reading: google places api 120 results limit workaround (python)
dist/
index.html
_headers
_astro/
hello.<hash>.js
If hello.<hash>.js is missing and your script text appears in index.html, the limit didn't apply. Re-check the config file name and make sure you rebuilt.
Verification checklist
- View source. Open the deployed page, choose view-source, and search for
<script. Every tag should have asrc. No tag should contain code between its opening and closing tags. - Check the header. Run
curl -I https://your-site.example/and confirm theContent-Security-Policyline is present and matches your file. - Console. Open DevTools, reload with the cache disabled, and confirm there are no "Refused to execute inline script" or "Refused to load the script" messages.
- Lighthouse. Run it in an incognito window with extensions off. Best Practices should show no console errors. The write-up reports 100 after fixing the beacon, but your score may differ for unrelated reasons.
- Behavior. Confirm the
#outtext changes. A CSP failure can be silent if you never look at the console.
Failure cases
| Symptom | Likely cause | Fix |
|---|---|---|
| Console error about a blocked script from a Cloudflare host; Best Practices drops (the write-up saw 100 to 92) | Automatic Web Analytics injection violates script-src 'self' | Disable automatic injection, or allow the beacon hosts from Cloudflare's docs |
| "Refused to execute inline script"; page feature does nothing | A script was inlined or marked is:inline | Set assetsInlineLimit: 0, remove is:inline, rebuild, confirm a file exists in dist/_astro |
| No CSP header in curl -I, or the policy never applies | _headers is not in the build output, has wrong indentation, or the path pattern is off | Put it in public/, confirm it lands in dist/, keep the rule indented under /* |
| Styles missing, errors mention style-src | Inlined <style> blocked by default-src 'self' | Emit CSS as files, or set a deliberate style-src |
What to expect next
Once the header is live, new violations usually come from changes, not from this setup: a new embed, a tag manager, or a dependency that injects a script. Keep the report-only trick handy, and rerun the checklist after any change to third-party code. If a future Astro release ships built-in CSP handling for your version, compare it against this manual approach before switching.



