Strict Astro CSP: Eliminate 'unsafe-inline' Completely

Learn how to enforce a strict Content Security Policy in Astro. Remove unsafe-inline using middleware nonces and Cloudflare Pages _headers.

A browser viewport frame with hydrating component islands lifting off the page, on a cluttered working desk, out-of-focus hand tools and a mug at the fr...

Do not allow unsafe-inline in your Content Security Policy. It bypasses the primary defense you set up against cross-site scripting (XSS) attacks. A strict policy blocks rogue scripts, but adding unsafe-inline opens the door for any injected inline code to run on your site.

Astro relies heavily on inline scripts. Its island architecture injects small <script type="module"> blocks to hydrate components and handle view transitions. If you use a dark mode toggle to prevent a Flash of Unstyled Content, you likely have another custom inline script in your <head>. A strict CSP blocks all of these by default.

A strict CSP starts with default-src 'none'. This fallback directive ensures that any resource type you fail to explicitly permit is blocked automatically. You then selectively open script-src, style-src, and img-src. When configuring Astro, you will quickly notice the friction: script-src 'self' allows your bundled JavaScript files to load, but it entirely blocks the inline scripts Astro needs for its component islands.

You can lock down an Astro deployment entirely without breaking interactivity. The implementation depends on your rendering mode. Server-side rendering (SSR) environments use dynamic nonces via Astro middleware. Statically generated (SSG) sites require a post-build script to compute SHA256 hashes and output a Cloudflare Pages _headers file.

Server-Side Nonces via Astro Middleware

When you run Astro in server or hybrid mode, your server processes every request. This allows you to generate a unique cryptographic nonce (a single-use string) for each visitor. The server places this nonce in the HTTP response header and tags every legitimate <script> with the exact same string. The browser blocks any script lacking this specific nonce.

Create an Astro middleware file to intercept requests and generate the token.

Create src/middleware.ts:

import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware(async (context, next) => {
  const nonce = crypto.randomUUID();
  context.locals.nonce = nonce;

  const response = await next();

  const csp = [
    `default-src 'none'`,
    `script-src 'self' 'nonce-${nonce}'`,
    `style-src 'self' 'unsafe-inline'`,
    `img-src 'self' data:`,
    `connect-src 'self'`
  ].join('; ');

  response.headers.set('Content-Security-Policy', csp);
  return response;
});

The middleware generates a standard UUID and attaches it to context.locals. The crypto.randomUUID() function is natively available in the Cloudflare Workers runtime and Node.js environments. Since the Astro middleware executes on the server side for every incoming request, the generated token is mathematically unique each time.

TypeScript will throw an error here until you declare the type for the locals object. Update your src/env.d.ts file to include the nonce property:

/// <reference types="astro/client" />
declare namespace App {
  interface Locals {
    nonce: string;
  }
}

Now you can inject the nonce into your own inline scripts within any Astro component.

<script nonce={Astro.locals.nonce}>
  console.log("This executes securely.");
</script>

Astro passes this nonce to its internal hydration scripts when configured properly, ensuring your interactive islands function normally while blocking injected attacks.

Static Sites Require SHA256 Hashes

Static pages lack a server to generate a fresh nonce on every page load. You cannot bake a single nonce into static HTML. An attacker would simply read the source, copy the static nonce, and bypass the protection. You must use cryptographic hashes instead.

When you use hashes, the browser computes the SHA256 sum of an inline script and verifies if it matches a hash allowed in your CSP header.

Astro can generate these hashes automatically and place them inside a <meta http-equiv="Content-Security-Policy"> tag. While convenient, <meta> tags cannot enforce advanced CSP directives like frame-ancestors, sandbox, or report-uri. To utilize the full CSP specification on a static site, you need actual HTTP response headers.

Cloudflare Pages applies HTTP headers using a plain text _headers file in the build directory. You can automate the creation of this file with a Node.js script that runs immediately after your Astro build.

Create scripts/generate-csp.mjs:

import fs from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';

async function buildCSPHeaders() {
  const distDir = path.join(process.cwd(), 'dist');
  const hashes = new Set();
  
  async function walk(dir) {
    const files = await fs.readdir(dir);
    for (const file of files) {
      const filePath = path.join(dir, file);
      const stat = await fs.stat(filePath);
      
      if (stat.isDirectory()) {
        await walk(filePath);
      } else if (filePath.endsWith('.html')) {
        const html = await fs.readFile(filePath, 'utf-8');
        const scriptRegex = /<script[^>]*>([\s\S]*?)<\/script>/gi;
        let match;
        
        while ((match = scriptRegex.exec(html)) !== null) {
          const content = match[1];
          if (content.trim()) {
            const hash = crypto.createHash('sha256').update(content).digest('base64');
            hashes.add(`'sha256-${hash}'`);
          }
        }
      }
    }
  }

  await walk(distDir);

  const hashList = Array.from(hashes).join(' ');
  const csp = `default-src 'none'; script-src 'self' ${hashList}; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:;`;
  const header = `/*\n  X-Frame-Options: DENY\n  X-Content-Type-Options: nosniff\n  Content-Security-Policy: ${csp}\n`;
  
  await fs.writeFile(path.join(distDir, '_headers'), header);
  console.log(`Generated CSP _headers with ${hashes.size} script hashes.`);
}

buildCSPHeaders();

This script recursively scans your dist directory, reads every .html file, and extracts the contents of every <script> tag. The regex [\s\S]*? ensures it matches multi-line scripts accurately. It calculates the base64-encoded SHA256 hash and ignores empty scripts or external tags without inline content. It uses a Set to deduplicate identical scripts across different pages, then outputs a single _headers file formatted for Cloudflare Pages.

Add this script to your build process in package.json:

{
  "scripts": {
    "build": "astro build && node scripts/generate-csp.mjs"
  }
}

Every time you run npm run build, your static site emits a _headers file with exact cryptographic hashes matching your Astro output.

The Cloudflare Auto Minify Trap

Deploying this hash-based setup to Cloudflare Pages requires one critical dashboard change. If you skip this, your CSP will block every script on your site.

Cloudflare provides a feature called Auto Minify. It strips whitespace, comments, and line breaks from your HTML right at the CDN edge, directly before serving the page to the visitor.

Because a SHA256 hash demands an exact byte-for-byte match, altering a single space inside a script tag changes its cryptographic hash entirely. The browser computes the hash of the minified script, compares it to the original hash generated during your local build, finds a mismatch, and blocks execution.

Disable this setting immediately:

  1. Open the Cloudflare dashboard and select your zone.
  2. Navigate to Speed -> Optimization -> Content Optimization.
  3. Under Auto Minify, uncheck HTML and JS.
  4. Purge your Cloudflare cache to clear the modified files.

Astro uses Vite to compress and minify your output during the build process. Edge minification adds no value here and permanently breaks cryptographic integrity.

Handling External Scripts

A strict policy built on hashes limits you to inline scripts. If your Astro project includes an external script, such as an analytics provider or a third-party widget, you must authorize that specific domain in your script-src directive.

Modify the _headers generation script to include your required domains:

const csp = `default-src 'none'; script-src 'self' https://analytics.example.com ${hashList};`;

If you use the SSR nonce approach, simply apply the nonce attribute to the external <script> tag. The browser permits the external fetch because the tag bears the correct security token.

What’s Next

Frequently Asked Questions

Does Astro support external script nonces?
Yes. If your CSP relies on nonces, you must add the nonce attribute to any external script tag so the browser permits it to execute.
What about inline styles and style-src?
Astro injects inline styles heavily. Hashing scoped component CSS is difficult. Many developers allow 'unsafe-inline' for styles, as CSS injection carries far less risk than JavaScript execution.
Can I use a Cloudflare Worker instead of _headers?
Yes. Cloudflare Pages Functions can attach headers dynamically. You still cannot generate nonces for statically cached HTML because the HTML itself is not dynamically rendered.
Sergej Voronko
Sergej Voronko
SAP Basis · Senior Operations Manager · Linux infrastructure engineer
About the author →

[discussion]

Comments are powered by Giscus — backed by GitHub Discussions. Sign in with GitHub to join the conversation.