Writing a Content Security Policy for a Static Site
A Content-Security-Policy is a list of places a page is allowed to load code and data from. Written well, it means an injected script cannot run and a compromised third-party script cannot send data anywhere unexpected. Written badly, it either breaks the site on deploy or includes 'unsafe-inline' and https: wildcards that allow nearly everything. The difference is process: inventory what the site really uses, write the narrowest policy that covers it, run it in report-only mode against real traffic, and only then enforce.
This guide takes a 700-page Astro documentation site on Cloudflare Pages through that process. The wider context is Security Headers and Hardening for Static Sites.
Prerequisites
- The ability to set response headers — a
_headersfile on Cloudflare Pages or Netlify,vercel.json, or server config. - An endpoint to receive violation reports. A small edge function is enough.
- A list of third-party services the site uses: analytics, embeds, forms, search, fonts.
Step 1: Inventory the Sources
Static sites make the inventory easy because all HTML is on disk. List every external origin referenced in the built output, grouped by attribute:
grep -rhoE '(src|href|action)="https?://[^/"]+' dist --include=*.html \
| sed -E 's/^(src|href|action)="//' | sort | uniq -c | sort -rn
grep -rhoE '<script(\s[^>]*)?>[^<]' dist --include=*.html | wc -l # inline scripts
grep -rhoE 'style="' dist --include=*.html | wc -l # inline styles
Then load one page of each template in Chrome with DevTools open and record anything requested at runtime that is not in the HTML — fonts from stylesheets, scripts loaded by other scripts, fetch calls. On the docs site the inventory was:
| Resource type | Sources found |
|---|---|
| Scripts | own bundles (/_astro/), 3 inline scripts (theme, search trigger, analytics loader), plausible.io |
| Styles | own stylesheets, 41 inline style attributes (from Markdown SVG diagrams) |
| Images | own origin, data: URIs for icons, img.example-cdn.net |
| Fonts | own origin |
| Connections | own origin (search fragments), plausible.io |
| Frames | www.youtube-nocookie.com on 9 pages |
| Form targets | forms.example.com (contact page) |
Step 2: Draft the Policy
Translate the inventory into directives, starting from default-src 'self' so anything unlisted is blocked:
Content-Security-Policy-Report-Only:
default-src 'self';
script-src 'self' 'sha256-3q2+7w…' 'sha256-Vx9aP…' 'sha256-kLm0Q…' https://plausible.io 'wasm-unsafe-eval';
style-src 'self' 'unsafe-hashes' 'sha256-…';
img-src 'self' data: https://img.example-cdn.net;
font-src 'self';
connect-src 'self' https://plausible.io;
frame-src https://www.youtube-nocookie.com;
form-action 'self' https://forms.example.com;
frame-ancestors 'none';
base-uri 'self';
object-src 'none';
upgrade-insecure-requests;
report-to csp-endpoint
Reporting-Endpoints: csp-endpoint="https://docs.example.com/api/csp-report"
The three inline scripts are allowed by hash rather than 'unsafe-inline'. Computing those hashes by hand is fragile; generate them in the build, as shown in Hash-Based CSP for Inline Scripts in Astro. 'wasm-unsafe-eval' is there for Pagefind's WebAssembly search engine and allows WebAssembly compilation only, not JavaScript eval.
Inline style attributes were the awkward part: 41 of them, all on SVG diagrams. Rather than allowing 'unsafe-inline' in style-src, the diagrams were moved to use presentation attributes and classes, leaving style-src 'self' achievable after one clean-up pass.
Step 3: Collect Reports
Deploy the header as Content-Security-Policy-Report-Only. The browser evaluates the policy and sends a report for every violation, but blocks nothing. The receiving endpoint on Cloudflare Workers:
// functions/api/csp-report.js (Cloudflare Pages Function)
export async function onRequestPost({ request, env }) {
const body = await request.json().catch(() => null);
const reports = Array.isArray(body) ? body : [body?.['csp-report'] ? { body: body['csp-report'] } : null];
for (const r of reports.filter(Boolean)) {
const b = r.body ?? r;
const src = b.sourceFile ?? b['source-file'] ?? '';
if (/^(chrome|moz|safari)-extension/.test(src)) continue; // extension noise
await env.CSP_LOG.writeDataPoint({
blobs: [b.effectiveDirective ?? b['effective-directive'], b.blockedURL ?? b['blocked-uri'], b.documentURL ?? b['document-uri']],
});
}
return new Response(null, { status: 204 });
}
Group reports by directive and blocked URL and review them daily for the first week. Each distinct entry is either a gap in the policy (add the source) or something that should not be there (remove it from the site).
Step 4: Fix, Then Enforce
The first week produced 18,400 reports. After filtering extensions, 214 remained, collapsing to seven distinct causes:
| Cause | Reports | Action |
|---|---|---|
| Analytics script loaded a second endpoint | 96 | added https://plausible.io to connect-src (already there, typo fixed) |
Search result excerpts used inline style | 51 | changed to classes in the result template |
| One old blog post embedded a CodePen iframe | 28 | replaced with a static screenshot and link |
| Theme toggle script hash changed after edit | 19 | hashes now generated at build time |
| A vendor font requested from a font CDN in an embed | 11 | embed moved behind click-to-load facade |
about:blank frames from a browser feature | 6 | ignored (browser noise) |
| Base64 image in an SVG | 3 | data: already allowed for img-src; SVG moved to file |
In week two, remaining reports were extension noise and the known about:blank entries. The header was switched from -Report-Only to enforcing, keeping report-to so new violations are still visible.
Keeping the Policy Current
A CSP is part of the site's configuration and changes with it. Two habits keep it from rotting. Put the policy in the repository — generated into _headers at build time from a small config object — so every change is reviewed. And add a CI check that parses the built HTML for external origins and inline scripts and fails if any appear that the policy would block. That catches the author who adds an embed or an inline script in a Markdown file long before a reader's browser does. Adding a vendor becomes a one-line policy change reviewed next to the code that needs it, which is exactly where the security decision belongs.
The other two failures were more interesting: one was a Markdown author pasting an embed snippet from a vendor's site, the other a dependency update that started injecting an inline style. Neither would have been noticed until readers' browsers started blocking content, and in enforcing mode that would have meant a silently broken page rather than a failed build.
Measured Impact
| Measure | Before | After |
|---|---|---|
| CSP | none | enforcing, no unsafe-inline in script-src or style-src |
| Mozilla Observatory | 70/100 (B, baseline headers only) | 115/100 (A+) |
| Inline scripts allowed | any | 3, by hash |
| External script origins allowed | unlimited | 1 |
| Pages changed to fit the policy | — | 11 (one blog post, search template, diagrams) |
| Reports per day, enforcing (non-extension) | — | 1–3 |
| LCP p75 change | — | none measurable |
Pitfalls & Rollback
- Starting in enforcing mode. Always run report-only first on real traffic; lab testing does not exercise every template and embed.
- Allowing
https:or*inscript-src. That permits scripts from any HTTPS origin and removes most of the protection. - Hand-maintained hashes. Any edit to an inline script changes its hash and breaks it. Generate hashes in the build.
- Forgetting
object-src 'none'andbase-uri. Without them, plugins and<base>tag injection remain open. - Not filtering extension reports. They drown real signal; filter by
source-filescheme. - One policy for previews and production. Preview hosts often inject a feedback toolbar script. Allow it only on preview hostnames, through a separate header rule, never in the production policy.
- Ignoring the 404 page. Error pages are often served through a different rule set; confirm the policy header is present on them too.
- Rollback: change the header name back to
Content-Security-Policy-Report-Only. The policy stops blocking immediately on the next deploy while reports keep flowing.
Conclusion
A strong CSP on a static site comes from a short, repeatable process: inventory the sources from the built HTML, draft a policy from default-src 'self' upwards, run it in report-only mode against real readers, fix what the reports show, and enforce once only noise remains. On a 700-page docs site that took two weeks and eleven page changes, produced a policy without 'unsafe-inline', and had no measurable performance cost.
FAQ
Where should I start when writing a CSP?
With an inventory of every origin and inline script the site actually uses, taken from the built HTML and a crawl with DevTools. Start from default-src 'self' and add only what the inventory shows is needed.
How long should report-only mode run?
Long enough to see every template and every third-party feature used by real readers, typically one to two weeks. Switch to enforcing once new reports are only from browser extensions.
Can I set CSP in a meta tag instead of a header?
Partly. A meta tag supports most fetch directives but not frame-ancestors, report-uri or report-to, and it only applies to content after the tag. Use the HTTP header where the host allows it.
Should the policy be identical on every page?
A single site-wide policy is easiest to maintain. Where a few pages need extra sources, such as video embeds, add a path-specific header rule for those pages rather than loosening the policy everywhere.
Related
- Parent: Security Headers and Hardening for Static Sites — the full header set.
- Hash-Based CSP for Inline Scripts in Astro — generating hashes automatically.
- Subresource Integrity for Third-Party Assets — verifying the scripts the policy allows.
- Setting Cache-Control Headers on Cloudflare Pages — the
_headersfile in depth. - Handling Form Submissions on a Static Site — keeping
form-action 'self'.