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 _headers file 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 typeSources found
Scriptsown bundles (/_astro/), 3 inline scripts (theme, search trigger, analytics loader), plausible.io
Stylesown stylesheets, 41 inline style attributes (from Markdown SVG diagrams)
Imagesown origin, data: URIs for icons, img.example-cdn.net
Fontsown origin
Connectionsown origin (search fragments), plausible.io
Frameswww.youtube-nocookie.com on 9 pages
Form targetsforms.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.

From inventory to directives Inventory items on the left map to directives on the right. Own bundles and hashed inline scripts and the analytics origin map to script-src. Own images, data URIs and the image CDN map to img-src. Search fragments and analytics beacons map to connect-src. The YouTube embed maps to frame-src. The form service maps to form-action. Everything else falls to default-src self. Each directive exists because the inventory found a use own bundles, 3 hashed inline, plausible.io own images, data: icons, image CDN search fragments, analytics beacon YouTube embed on 9 pages contact form service script-src img-src connect-src frame-src form-action everything not listed → default-src 'self' → blocked if cross-origin
A policy built from an inventory is short and specific; a policy built from error messages tends to accumulate wildcards.

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:

CauseReportsAction
Analytics script loaded a second endpoint96added https://plausible.io to connect-src (already there, typo fixed)
Search result excerpts used inline style51changed to classes in the result template
One old blog post embedded a CodePen iframe28replaced with a static screenshot and link
Theme toggle script hash changed after edit19hashes now generated at build time
A vendor font requested from a font CDN in an embed11embed moved behind click-to-load facade
about:blank frames from a browser feature6ignored (browser noise)
Base64 image in an SVG3data: 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.

Daily reports during rollout A line of non-extension CSP reports per day over fourteen days. Days one to three show 40 to 45 reports a day. Fixes on days four to six bring it down to about 10. Days eight to fourteen hover at 1 to 3. Enforcement begins on day ten, with no increase afterwards. Non-extension violation reports per day 0 25 50 enforcing from day 10 fixes ship day 1 day 14 ~310,000 page views over the period; 18,400 extension reports filtered in week one alone
The switch to enforcing is safe when the report line is flat at noise level — here, from day eight.

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.

Policy check in the build The build writes HTML and generates the _headers file from a policy config. A check scans the HTML for external origins and inline scripts and compares them with the policy. If everything is covered, the deploy continues. If a new origin or unhashed script appears, the pull request fails with the file and the directive that would block it. Catch policy gaps at review, not in readers' browsers build HTML + _headers scan vs policy origins, inline hashes all covered → deploy gap → PR fails guides/embeds.html · frame-src In six months the check failed nine pull requests; seven added a vendor and updated the policy in the same PR
The check turns policy maintenance into a normal review conversation instead of a production incident.

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

MeasureBeforeAfter
CSPnoneenforcing, no unsafe-inline in script-src or style-src
Mozilla Observatory70/100 (B, baseline headers only)115/100 (A+)
Inline scripts allowedany3, by hash
External script origins allowedunlimited1
Pages changed to fit the policy11 (one blog post, search template, diagrams)
Reports per day, enforcing (non-extension)1–3
LCP p75 changenone 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 * in script-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' and base-uri. Without them, plugins and <base> tag injection remain open.
  • Not filtering extension reports. They drown real signal; filter by source-file scheme.
  • 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.