Skip to main content

Web Security Headers and CSP Guide (2026): HSTS, Content Security Policy, and Cloudflare Pages Examples

By Pashalis LaoutarisUpdated: Category: Security31 min read

Security headers are the cheapest security work you will ever do. A few lines of configuration tell the browser to refuse plain HTTP, block injected scripts, stop other sites from framing your pages, and keep private data out of referrer URLs. They cost nothing at runtime, and they protect every page at once.

They are also easy to get wrong. A Content Security Policy that is too loose gives a false sense of safety. One that is too strict breaks your site in ways that only show up in the browser console. Most guides stop at a list of headers to copy. This one explains what each header does, which values to use in 2026, and how to roll them out without breaking anything.

I use this very site as the test case. It is a static Astro site on Cloudflare Pages, so every example applies directly to that stack. I also turned on Astro’s built-in CSP feature in a test build and loaded the pages in headless Chromium to count the violations. Astro’s automatic CSP skipped every is:inline script on this site and broke all code highlighting. Section 11 has the measured results.

The facts here come from MDN, the W3C specifications, OWASP, and Cloudflare’s documentation, which I checked on November 26, 2026. This article belongs to my security series. It pairs well with my guides to passkeys and 2FA, SAST and DAST tools, and supply chain security.

Table of Contents

  1. The Short Answer
  2. How Security Headers Work
  3. Strict-Transport-Security (HSTS)
  4. Content Security Policy Basics
  5. Strict CSP: Nonces, Hashes, and strict-dynamic
  6. Trusted Types
  7. Clickjacking Protection
  8. The Other Headers
  9. Reporting and Safe Rollout
  10. Cloudflare Pages: The _headers File
  11. Case Study: Astro’s Built-In CSP on This Site
  12. Nonces on Cloudflare with Pages Functions
  13. Testing Your Headers
  14. Common Mistakes
  15. Frequently Asked Questions
  16. Conclusion
  17. References

1. The Short Answer

Start with the headers below. They are safe for almost every site, and only the Content Security Policy needs real tuning.

Header Recommended value What it stops
Strict-Transport-Security max-age=31536000; includeSubDomains (add preload later) Downgrade to HTTP, cookie theft on open Wi-Fi
Content-Security-Policy A strict policy with nonces or hashes (see section 5) Cross-site scripting, data injection
X-Content-Type-Options nosniff MIME sniffing attacks
Referrer-Policy strict-origin-when-cross-origin Leaking full URLs to other sites
Permissions-Policy Disable features you do not use, such as camera=() Abuse of powerful browser APIs
Cross-Origin-Opener-Policy same-origin Cross-window attacks and some side channels
Cross-Origin-Resource-Policy same-origin or same-site Other sites embedding your private resources
X-Frame-Options DENY (backup for frame-ancestors) Clickjacking in very old browsers

Three rules cover most of the value.

  • Turn on HSTS first: It is one line, and it removes a whole class of network attacks.
  • Treat CSP as a project: Deploy it in report-only mode, fix what breaks, and then enforce it.
  • Never set X-XSS-Protection to 1: The old browser XSS filter is gone, and OWASP recommends 0 or no header at all.

Start here: a safe starter file

If you want safe defaults today, paste this into a Cloudflare Pages _headers file and adjust the TODO lines. It enforces only the CSP directives that almost never break a site. The full policy runs in report-only mode, so it logs problems without blocking anything.

# TODO 1: raise the HSTS max-age to 31536000 after a week without problems.
# TODO 2: add hashes or nonces for inline scripts, then enforce the report-only policy.
# TODO 3: point Reporting-Endpoints at your own report collector.
/*
  Strict-Transport-Security: max-age=604800; includeSubDomains
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin
  Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=()
  Cross-Origin-Opener-Policy: same-origin
  X-Frame-Options: DENY
  Content-Security-Policy: object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
  Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; report-to csp-endpoint
  Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"

The enforced Content-Security-Policy line holds only the four directives that rarely break anything. The browser enforces the first policy and only reports on the second. Once the reports are clean, sections 5 and 9 explain how to make the strict policy enforcing.

2. How Security Headers Work

A security header is an instruction from your server to the browser. The browser reads it with each response and changes its own behavior. Your server does not enforce anything. The protection only works because modern browsers agree to follow the rules.

That has two consequences. First, headers protect your users, not your server. A header cannot stop an attacker who sends requests with curl. Second, headers are a second line of defense. A strict CSP limits the damage of a cross-site scripting bug, but you should still fix the bug.

Headers apply per response. A header on your HTML page does not cover a JSON endpoint or an image unless that response carries it too. Some headers matter mostly on HTML documents, such as CSP and the framing rules. Others, such as X-Content-Type-Options, help on every response.

3. Strict-Transport-Security (HSTS)

HSTS tells the browser to use HTTPS for your domain for a set time. After the first visit, the browser rewrites every http:// link to https:// before it sends anything. An attacker on the same network can no longer catch that first plain request and redirect the user.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

The parts mean the following.

  • max-age: The number of seconds the browser remembers the rule. One year is 31,536,000 seconds.
  • includeSubDomains: The rule also covers every subdomain. Check that all of them really serve HTTPS first.
  • preload: You consent to being added to the preload list built into browsers.

The preload list closes the last gap. Without it, the very first visit to your site can still go over HTTP. With it, browsers know your domain is HTTPS-only before they ever connect. The submission form at hstspreload.org requires a max-age of at least one year, includeSubDomains, and the preload token.

Preloading is hard to undo. Removal takes months to reach users, because it ships with browser releases. Start with a short max-age, such as one week, and raise it after you confirm nothing breaks. Add preload only when you are sure every subdomain will stay on HTTPS for good.

4. Content Security Policy Basics

A Content Security Policy lists where a page may load content from. If an attacker injects a <script> tag, the browser checks the policy and refuses to run it. CSP is the most powerful security header, and the one that needs the most care.

A policy is a list of directives separated by semicolons. Each directive names a type of content and the sources allowed for it.

Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.com; object-src 'none'

The directives that matter most

Directive Controls Typical value
default-src Fallback for most fetch directives 'self'
script-src JavaScript Nonces or hashes (see section 5)
style-src CSS 'self', plus hashes if needed
img-src Images 'self' plus known hosts
connect-src fetch, XHR, WebSocket, EventSource 'self' plus your API hosts
font-src Web fonts 'self' or a font host
frame-src Pages you embed in iframes Only the hosts you embed
object-src Plugins such as <object> and <embed> 'none'
base-uri The <base> tag 'self' or 'none'
form-action Where forms may submit 'self'
frame-ancestors Who may frame your page 'none' or 'self'

Three directives do not fall back to default-src, and people forget them. These are base-uri, form-action, and frame-ancestors, so set them explicitly. A missing base-uri lets an injected <base> tag redirect every relative script URL to an attacker’s server.

Never forget these four: Put object-src 'none', base-uri 'none' or 'self', form-action 'self', and frame-ancestors 'none' or 'self' in every policy. They cost nothing, they rarely break anything, and attackers rely on the gaps they leave.

Source keywords

  • 'self': The same origin as the page. Scheme, host, and port must all match.
  • 'none': Nothing at all.
  • 'unsafe-inline': Allows inline scripts or styles. For scripts, this disables most of the protection.
  • 'unsafe-eval': Allows eval() and similar functions, so avoid it.
  • 'wasm-unsafe-eval': Allows WebAssembly compilation without allowing JavaScript eval.
  • 'nonce-...' and 'sha256-...': Allow specific inline scripts or styles. Section 5 covers both.
  • 'strict-dynamic': Lets trusted scripts load further scripts.

Why allowlists fail

The classic CSP lists trusted hosts, such as script-src 'self' https://cdn.example.com. Research from Google found that this style is usually bypassable. Popular CDNs host old libraries and JSONP endpoints, and an attacker can load those to run their own code. A host allowlist also grows forever as you add services.

That research led to “strict CSP,” which trusts specific scripts instead of whole hosts. It is the approach that the W3C, Google, and OWASP now recommend.

5. Strict CSP: Nonces, Hashes, and strict-dynamic

A strict CSP allows a script only if your server marked it as trusted. There are two ways to mark it.

Nonce-based policy

A nonce is a random value that your server generates fresh for every response. It goes into both the header and each script tag.

Content-Security-Policy: script-src 'nonce-R4nd0mV4lu3' 'strict-dynamic'; object-src 'none'; base-uri 'none'
<script nonce="R4nd0mV4lu3" src="/app.js"></script>
<script nonce="R4nd0mV4lu3">
  initApp();
</script>

An injected script has no valid nonce, so it does not run. The attacker cannot guess the nonce, because it changes on every page load. Use at least 128 bits of randomness, which is 16 random bytes encoded as base64.

Nonces need a server that renders each response. They do not fit a static site where every visitor gets the same file, unless something at the edge rewrites the HTML. Section 12 shows how to do that on Cloudflare.

Hash-based policy

A hash policy lists the SHA-256 hash of each allowed inline script. The browser hashes every inline script it sees and runs only those that match.

Content-Security-Policy: script-src 'sha256-VTlNaT0DAyONwYLZKbQiqFNQbqHkDYtNsAwK//yQXCU=' 'strict-dynamic'

Hashes suit static sites, because the script content is fixed at build time. The catch is that any change to the script, even one space, changes the hash. A build tool should compute hashes for you. You can compute one by hand with OpenSSL.

printf '%s' 'initApp();' | openssl dgst -sha256 -binary | openssl base64

What strict-dynamic does

Modern apps load scripts from other scripts. A bundler adds a chunk on demand, or an analytics loader injects its own tag. Listing every one of those is impractical.

The 'strict-dynamic' keyword solves this problem. A script that you trusted with a nonce or hash may load further scripts, and the browser trusts those too. In browsers that support it, 'strict-dynamic' also makes the browser ignore host allowlists and 'self' in script-src. That is deliberate, because it keeps an old allowlist from weakening the policy.

This is the strict policy that web.dev documents. It works with nonces, and you can swap the nonce for hashes on a static site.

Content-Security-Policy:
  script-src 'nonce-{RANDOM}' 'strict-dynamic' https: 'unsafe-inline';
  object-src 'none';
  base-uri 'none';

The https: and 'unsafe-inline' parts look alarming, but they are a fallback for very old browsers. A browser that understands nonces ignores 'unsafe-inline'. A browser that understands 'strict-dynamic' ignores https:. Every current browser understands both, so they only matter for legacy clients. They are harmless in modern browsers. You can remove them once you no longer support very old browsers, which makes the policy easier to read.

Inline event handlers and style attributes

Strict CSP blocks inline event handlers such as onclick="..." and javascript: URLs. Move that code into a script that calls addEventListener. The 'unsafe-hashes' keyword can allow specific handler hashes, but rewriting the handler is cleaner.

Styles work in a similar way. A style-src policy without 'unsafe-inline' blocks style="..." attributes. That breaks many syntax highlighters and UI libraries, as section 11 shows. Style injection is much less dangerous than script injection, so many sites keep 'unsafe-inline' for style-src and stay strict on scripts. That is a reasonable trade.

Finer control: the -elem and -attr directives

CSP Level 3 splits script-src and style-src into finer directives. script-src-elem covers <script> elements, and script-src-attr covers inline event handlers such as onclick. style-src-elem and style-src-attr do the same for <style> elements and style attributes. When one of them is missing, the browser falls back to the general directive.

They help with the highlighter problem above. You can allow style attributes without allowing <style> elements.

Content-Security-Policy: style-src 'self'; style-src-attr 'unsafe-inline'

Here, <style> blocks and stylesheets must still come from your own origin or a hash. Only style attributes, such as those from Shiki, are allowed inline. Keep script-src-attr 'none' in mind as well, because it blocks every inline event handler even if a looser script-src slips in later.

6. Trusted Types

A strict CSP stops injected script tags. It does not stop DOM-based cross-site scripting, where your own trusted JavaScript writes attacker-controlled text into innerHTML or a similar sink.

Trusted Types closes that gap. When you enable it, the browser refuses plain strings in dangerous sinks such as innerHTML, outerHTML, document.write, and script.src. Your code must pass a typed object created by a policy you define, so all risky HTML goes through one reviewed function.

Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-html
const policy = trustedTypes.createPolicy("app-html", {
  createHTML: (input) => DOMPurify.sanitize(input),
});

element.innerHTML = policy.createHTML(userComment); // allowed
element.innerHTML = userComment; // throws a TypeError

Trusted Types reached Baseline in early 2026. Chromium has supported it since version 83 in 2020, Safari added it in version 26, and Firefox shipped it in version 148 in February 2026. You can now rely on it in all major engines.

Roll it out the same way as CSP. Use a Content-Security-Policy-Report-Only header first, collect the violations, and fix each sink. Frameworks such as Angular and Lit already integrate with Trusted Types.

Users on older browser versions still exist, so feature-detect before you call the API.

const policy = window.trustedTypes
  ? trustedTypes.createPolicy("app-html", { createHTML: (s) => DOMPurify.sanitize(s) })
  : { createHTML: (s) => DOMPurify.sanitize(s) }; // same sanitizer, plain string

Older browsers then get the same sanitizer without enforcement. The W3C also publishes a Trusted Types polyfill for the transition period.

Trusted Types complements a strict CSP, and it does not replace it. CSP stops injected script tags, while Trusted Types stops your own code from writing unsafe HTML, so you want both.

7. Clickjacking Protection

Clickjacking loads your page in an invisible frame on an attacker’s site. The user thinks they are clicking the attacker’s button, but they are really clicking yours, such as “Delete account.”

The modern defense is the frame-ancestors directive of CSP.

Content-Security-Policy: frame-ancestors 'none'

Use 'none' if nobody should frame your pages. Use 'self' if only your own site frames them. List specific origins if partners embed your widget.

X-Frame-Options is the older header with the same purpose. When both are present, current browsers follow frame-ancestors. Sending X-Frame-Options: DENY as well costs nothing and helps very old clients.

frame-ancestors only works in a real HTTP header. Browsers ignore it inside a <meta> tag, which matters for static sites, as section 11 explains.

8. The Other Headers

X-Content-Type-Options

X-Content-Type-Options: nosniff

This stops the browser from guessing a file’s type from its content. Without it, a user-uploaded file served as text/plain might be treated as HTML or JavaScript. Set it on every response.

Referrer-Policy

Referrer-Policy: strict-origin-when-cross-origin

This value sends the full URL to your own site, only the origin to other sites, and nothing when moving from HTTPS to HTTP. It is already the default in modern browsers. Setting it explicitly protects you from a browser that behaves differently, and it documents your intent. Use no-referrer if your URLs contain anything sensitive, such as reset tokens.

Permissions-Policy

Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=()

This disables powerful browser features for your page and any frames inside it. An empty list () means nobody may use the feature. If an attacker injects a script or a third-party frame misbehaves, it still cannot open the camera. List the features you never use.

Cross-origin isolation headers

Three newer headers control how your pages interact with other origins.

  • Cross-Origin-Opener-Policy: same-origin: Puts your page in its own browsing context group. Windows from other origins that you open, or that open you, lose their reference to your window.
  • Cross-Origin-Resource-Policy: same-origin: Stops other sites from loading your resources with <img> or <script> tags. Use same-site if your subdomains share resources, and cross-origin for public assets.
  • Cross-Origin-Embedder-Policy: require-corp: Requires every resource your page loads to opt in. It is needed for features such as SharedArrayBuffer, but it breaks third-party images and scripts that do not send CORP headers.

COOP and CORP are safe defaults for most sites. Add COEP only when you need cross-origin isolation, and test it carefully. The credentialless value of COEP is a gentler option, because it loads cross-origin resources without cookies.

Headers you can drop

  • X-XSS-Protection: Browsers removed the XSS auditor, and the header could even introduce leaks. Send 0 or nothing.
  • Expect-CT: Certificate Transparency is now enforced by default, and the header is deprecated.
  • Public-Key-Pins: HPKP was removed from browsers years ago, because a mistake could lock users out.

9. Reporting and Safe Rollout

Never switch on a new CSP in enforcing mode on a busy site. Use the report-only header first. The browser logs and reports what it would have blocked, but it blocks nothing.

Content-Security-Policy-Report-Only: script-src 'self' 'strict-dynamic' 'sha256-...'; object-src 'none'; report-to csp-endpoint
Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"

The modern way to receive reports is the Reporting API. You name an endpoint in Reporting-Endpoints and refer to it with the report-to directive. The older report-uri directive is deprecated but still widely supported, so many sites send both during the transition.

You can run a report-only policy next to an enforcing one. That lets you test a stricter policy while the current one keeps protecting users.

A rollout plan that works

  1. Inventory: List every script, style, font, image host, and API your pages use.
  2. Draft: Write the policy, starting from the strict template in section 5.
  3. Report-only: Deploy it with Content-Security-Policy-Report-Only and collect reports for at least a week. Filter out chrome-extension:// and moz-extension:// sources from the start, so the feed stays readable.
  4. Fix: Move inline handlers into scripts, add hashes or nonces, and remove dead third-party code.
  5. Enforce: Switch to Content-Security-Policy, and keep reporting on.
  6. Watch: Alert on sudden spikes in reports, because they often mean a broken deploy or an attack.

Expect noise in the reports. Browser extensions inject scripts into pages, and those show up as violations. Filter reports whose source is chrome-extension or moz-extension before you act on them.

10. Cloudflare Pages: The _headers File

Cloudflare Pages lets you set response headers with a plain text file named _headers in your build output. For an Astro site, put it in the public/ folder, and Astro copies it to dist/ unchanged.

Syntax

Each rule is a URL pattern followed by indented header lines.

/*
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin

/admin/*
  X-Robots-Tag: noindex

/assets/*
  ! Access-Control-Allow-Origin
  Cache-Control: public, max-age=31536000, immutable
  • Splats: * matches any path segment sequence, as in /assets/*.
  • Placeholders: :name matches one path segment and can be reused in values.
  • Removing headers: A line that starts with ! removes a header, including one that Pages adds by default.
  • Order matters: Rules apply in file order, and ! only removes what earlier rules added. Put narrow rules after broad ones.
  • Merging: When several rules match the same path, Pages applies all of them. If two rules set the same header, Pages joins the values with a comma.

That last point has a sharp edge for CSP. A comma inside a Content-Security-Policy value separates two policies, and the browser enforces both. Two matching rules that each set a CSP therefore give you the strictest combination of the two. To give one path a different policy, detach the header with ! and set it again.

Limits and gotchas

Cloudflare’s documentation lists two limits. You may define up to 100 header rules, and each line may be at most 2,000 characters, including the header name. A long CSP can hit that line limit, so keep the policy lean.

The bigger gotcha is scope. The _headers file only applies to static assets. If you use Pages Functions or server-side rendering, headers for those responses must come from the function’s Response object instead.

This site’s headers

Here is the _headers file that laoutaris.org deploys today.

/*
  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  X-Frame-Options: DENY
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin
  Permissions-Policy: accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()
  Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://cdnjs.cloudflare.com https://static.cloudflareinsights.com; worker-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' https://cloudflareinsights.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none';

I checked the live response with curl on November 26, 2026, and every header arrived as written.

curl -sI https://laoutaris.org/

The CSP line is about 420 characters, well under the limit. Here is why each part of the policy is there.

  • default-src 'self': The fallback for every fetch directive that is not listed.
  • script-src: Own scripts, Cloudflare’s analytics beacon, and 'wasm-unsafe-eval' for the Pagefind search index, which runs on WebAssembly.
  • worker-src: Pagefind loads its search worker from the site itself.
  • img-src 'self' data: https:: Blog posts embed images from other HTTPS hosts.
  • connect-src: Allows the analytics beacon to send its data.
  • object-src 'none': Blocks plugins entirely.
  • base-uri, form-action, frame-ancestors: The three directives that do not fall back to default-src, so they are set explicitly.

Its weak spot is 'unsafe-inline' in script-src. That keyword allows any inline script, including an injected one. It is there because the site has several inline scripts, such as the theme switcher and the mobile menu. The next section shows what happens when you try to remove it.

The response also carries Access-Control-Allow-Origin: *, which I did not set. Pages adds it to static assets by default. For public, cookie-free content, that is harmless, because CORS with a wildcard never sends credentials. If you serve anything private from Pages, remove it with a ! Access-Control-Allow-Origin line.

11. Case Study: Astro’s Built-In CSP on This Site

Astro has a built-in CSP feature. You enable it in the config, and Astro hashes the scripts and styles it renders. It then adds the policy to each page as a <meta http-equiv="content-security-policy"> tag.

// astro.config.mjs
export default defineConfig({
  security: { csp: true },
});

I wanted to know whether this site could drop 'unsafe-inline' that way. So I built the site with Astro 7.4.13 and security: { csp: true }, using a separate output folder. Then I served both builds locally and loaded four pages in headless Chromium. A small script counted the CSP violations that the browser logged.

What Astro generated

The build printed one warning straight away. It said that Shiki syntax highlighting uses inline styles that are not compatible with CSP. Shiki is Astro’s default code highlighter.

The home page received a meta tag with 11 script hashes and 2 style hashes, along with 'self'. The tag covered only script-src and style-src.

The results

Page Current build with header CSP Astro CSP build
Home page 0 violations 2 inline scripts blocked
Blog index 0 violations 2 inline scripts blocked
LLM API cost calculator 0 violations, works 2 inline scripts blocked, works
Passkeys article (many code blocks) 0 violations 4 scripts and 1,403 styles blocked

The calculator still worked, because its own script is bundled by Astro, and Astro hashed it. Adding my header CSP on top of the Astro build changed nothing. When a page has two policies, the browser enforces both, so the strictest rule wins.

Why the scripts failed

I hashed every inline script in the generated HTML and compared the results with the meta tag. The pattern was clear.

  • Scripts that Astro processes were hashed: Both bundled module scripts on the home page matched.
  • Scripts marked is:inline were not hashed: Astro skips them, because it does not process their content. The mobile menu, the cookie banner, the post layout script, and the share buttons all use is:inline on this site.
  • The theme script still ran: It sits in the <head> before the meta tag. A meta policy only applies to content that comes after it, so the theme script escaped. That is an accident of position, not a feature.

The share buttons add a second problem. They use define:vars to pass each page’s URL into the script, so the script text differs on every page. A single site-wide hash in _headers can never match it.

This is the message Chromium logged for each blocked script, shortened here.

Executing inline script violates the following Content Security Policy directive
'script-src 'self' 'sha256-pLGsp3/oj4BMvGIoA8aR58k0HFQxw8tnZCFNWjzHDNU=' ...'.
Either the 'unsafe-inline' keyword, a hash ('sha256-pABmPdX7kSLLQVK6SIjtm/O0XQdBJOdq3TFkNJ7m4cM='),
or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.

The fix for a message like this is not to add 'unsafe-inline' back. Find the script, then either let the build tool hash it or add its hash yourself. Chromium prints the exact hash it needs in the same message, as shown above, which makes the second option quick. Check that the script is really yours before you trust its hash.

Why the code blocks lost their colors

Shiki colors each token with a style="color:..." attribute. The Passkeys article has 1,403 of them. A style-src with hashes and no 'unsafe-inline' blocks every style attribute. I checked one token’s computed color before and after. It changed from the theme’s pink to the page’s default gray, so every code block lost its highlighting.

What a meta tag cannot do

A CSP in a meta tag has fixed limits. Browsers ignore frame-ancestors, report-uri, and sandbox there. It also does not cover anything that appears before the tag. For those reasons, a meta tag can add a strict script rule, but it cannot replace the header.

What I would change on this site

The test points to a plan.

  1. Keep the header CSP for frame-ancestors, object-src, and the other directives that a meta tag cannot carry.
  2. Convert is:inline scripts into normal Astro scripts where possible, so Astro bundles and hashes them.
  3. Replace define:vars in the share buttons with a data-url attribute that the script reads, so its content stays fixed.
  4. Hash the one script that must stay inline, the theme switcher, and put that hash in the header policy.
  5. Keep 'unsafe-inline' for style-src, or switch from Shiki to class-based highlighting such as Prism. Style injection is far less dangerous than script injection.

After those steps, script-src can drop 'unsafe-inline'. That is the change that gives CSP its real power against cross-site scripting.

12. Nonces on Cloudflare with Pages Functions

Hashes fit a static site. If your pages contain inline scripts that change on every request, you need nonces. On Cloudflare Pages, a middleware function can add them at the edge.

The function below runs before each request. It fetches the static page, rewrites every script tag with a fresh nonce, and sets the matching header. It uses HTMLRewriter, Cloudflare’s streaming HTML parser.

// functions/_middleware.js
export async function onRequest(context) {
  const response = await context.next();
  const type = response.headers.get("content-type") || "";
  if (!type.includes("text/html")) return response;

  const bytes = crypto.getRandomValues(new Uint8Array(16));
  const nonce = btoa(String.fromCharCode(...bytes));

  const rewritten = new HTMLRewriter()
    .on("script", {
      element(el) {
        el.setAttribute("nonce", nonce);
      },
    })
    .transform(response);

  const headers = new Headers(rewritten.headers);
  headers.set(
    "Content-Security-Policy",
    `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`,
  );
  return new Response(rewritten.body, { status: rewritten.status, headers });
}

There is a serious flaw in this naive version, and you must understand it. It adds the nonce to every script in the response, including a script an attacker injected through a stored XSS bug. The nonce then protects nothing.

The fix is to mark trusted scripts at build time and nonce only those. For example, add a data-trusted attribute to your own script tags in the source, and match on it.

new HTMLRewriter().on("script[data-trusted]", {
  element(el) {
    el.setAttribute("nonce", nonce);
    el.removeAttribute("data-trusted");
  },
});

An attacker who controls page content could still add data-trusted to an injected tag. So this approach only helps against injection that happens in the browser, such as DOM XSS, and not against server-side template injection. For a site whose HTML is static and built from trusted sources, hashes remain the simpler and stronger choice.

I did not deploy this function. The code follows Cloudflare’s documented onRequest, context.next(), and HTMLRewriter APIs, but test it on a preview deployment before you use it. Also note that running a function on every request uses your Pages Functions quota, while plain static files do not.

Which approach to use

Your site Use
Static site with fixed inline scripts Hashes computed at build time, in _headers or a meta tag
Server-rendered pages A fresh nonce per response, set by the server
Third-party loaders, such as analytics Add 'strict-dynamic' and trust only the loader
Static site with per-page inline scripts Refactor them to fixed scripts, then use hashes

For most static sites, hashes at build time are the recommended path. Edge noncing is a last resort for HTML you cannot change at build time.

13. Testing Your Headers

From the command line

curl -sI shows the headers of any URL. Check your HTML pages, but also a JSON endpoint, an image, and your 404 page. Those often miss headers that the main pages have.

curl -sI https://example.com/ | grep -iE "strict-transport|content-security|x-content-type|referrer|permissions|cross-origin"

Online scanners

  • MDN HTTP Observatory: Mozilla moved its Observatory to MDN in 2024. It grades your headers and explains each finding.
  • Google CSP Evaluator: Paste a policy, and it flags known bypasses, such as risky CDN hosts in script-src.
  • securityheaders.com: A quick grade with clear advice for each missing header.

In the browser

Open the developer tools console, reload the page, and look for messages that mention Content Security Policy. Chromium also lists CSP problems in the Issues panel. That is where I would start when a page suddenly breaks after a policy change.

In CI

Add a check that fails the build when a key header goes missing. Security headers break quietly, so a test is the only way to notice. This script checks the headers and the four directives that every CSP needs.

// check-headers.mjs: fail CI when key security headers are missing or weakened.
// usage: node check-headers.mjs https://example.com/ [more URLs...]
const REQUIRED = {
  "strict-transport-security": (v) => /max-age=\d+/.test(v),
  "x-content-type-options": (v) => v.toLowerCase() === "nosniff",
  "referrer-policy": (v) => v.length > 0,
  "content-security-policy": (v) =>
    ["object-src", "base-uri", "form-action", "frame-ancestors"].every((d) => v.includes(d)),
};

let failed = 0;
for (const url of process.argv.slice(2)) {
  const res = await fetch(url, { redirect: "manual" });
  for (const [name, ok] of Object.entries(REQUIRED)) {
    const value = res.headers.get(name);
    if (value === null || !ok(value)) {
      failed++;
      console.log(`FAIL ${url} ${name}: ${value ?? "missing"}`);
    }
  }
  console.log(`checked ${url} (${res.status})`);
}
process.exit(failed ? 1 : 0);

I ran it against four URLs on this site, including a 404 page and the XML sitemap, and all of them passed. Against example.com, which sends none of these headers, it reported four failures and exited with code 1. Run it against each preview deployment, and add your API endpoints and error pages to the list.

After a deploy, also watch the volume of CSP reports. A sudden spike usually means a broken release or an active attack, and either one deserves an alert.

14. Common Mistakes

  1. Using 'unsafe-inline' in script-src without nonces or hashes. This disables most of what CSP offers against XSS.
  2. Forgetting base-uri, form-action, and frame-ancestors. They do not inherit from default-src.
  3. Allowlisting whole public CDNs. A host like a public CDN serves thousands of scripts, and some of them can be abused.
  4. Putting frame-ancestors in a meta tag. Browsers ignore it there, so the page stays frameable.
  5. Preloading HSTS too early. Check every subdomain first, because removal from the list takes months.
  6. Enforcing a new CSP without a report-only phase. You find out what broke from angry users instead of reports.
  7. Applying headers only to HTML. Uploaded files and API responses need nosniff and sensible CORS headers too.
  8. Setting headers in _headers for Pages Functions responses. They do not apply there, so set them in the function.
  9. Keeping X-XSS-Protection: 1; mode=block. It does nothing in modern browsers and caused leaks in old ones.
  10. Treating a good scanner grade as the goal. A policy with 'unsafe-inline' can still look fine on paper.

15. Frequently Asked Questions

Does a CSP replace output encoding and sanitization?

No, it does not. CSP is a safety net for the bugs you missed. You should still escape output and sanitize user HTML. A strict CSP turns many XSS bugs into harmless console errors, which buys you time to fix them.

Should I use nonces or hashes?

Use hashes for static sites and pages whose inline scripts never change. Use nonces when your server renders HTML per request. Both are equally strong when used correctly.

Is a CSP in a meta tag good enough?

It is better than nothing, but it is weaker than a header. It cannot set frame-ancestors or reporting, and it does not protect content above it. Use a header whenever your host allows it.

Can I use CSP with Google Analytics or other third-party scripts?

Yes, you can, and 'strict-dynamic' makes it simple. You only need to trust the loader script with a nonce or hash. The scripts it loads inherit that trust. You still need to allow their network calls in connect-src and their images in img-src.

What about Cloudflare’s own scripts, such as Web Analytics?

When Cloudflare injects the Web Analytics beacon automatically, it adds a script from static.cloudflareinsights.com. Your policy must allow that host, or a nonce or hash must cover the loader. This site allows the host in script-src and connect-src for that reason.

Does HSTS slow down my site?

No, it does not. It makes later visits slightly faster, because the browser skips the HTTP-to-HTTPS redirect.

16. Conclusion

Most security headers are simple. HSTS, nosniff, a referrer policy, a permissions policy, and COOP take minutes to add and rarely break anything, so add them today.

Content Security Policy is different. It is the header that actually stops cross-site scripting, and it only works when you stop trusting inline scripts as a group. That means hashes on static sites, nonces on dynamic ones, and 'strict-dynamic' for scripts that load other scripts.

My own test showed how easy it is to fool yourself. Astro’s automatic CSP looks complete, yet it skipped every is:inline script and broke code highlighting on this site. Test any policy in a real browser before you trust it, and roll it out in report-only mode first. Browser support and tooling keep improving, so treat this guide as accurate as of late November 2026.

17. References

Standards and documentation

Cloudflare and Astro

Tools


Back to All Posts
Share this post:
Share on X
Share on LinkedIn
Share on Reddit
Share on Facebook
Copy Link
Copied!