Open-Source Wikis

/

Astro

/

Features

/

Content Security Policy

withastro/astro

Content Security Policy

Astro 6 promoted Content Security Policy generation to a first-class subsystem. With the right config, every rendered page gets a fresh <meta http-equiv="Content-Security-Policy"> (or response header) with a per-request nonce, hashes for inline scripts and styles, and the directives the user has declared.

Purpose

Make it cheap for Astro projects to ship a strict CSP without writing every directive by hand. The framework knows what scripts and styles it emits, so it can compute hashes, generate nonces, and combine them with user directives.

Key files

File Purpose
packages/astro/src/core/csp/runtime.ts Runtime helpers (nonce generation, header building).
packages/astro/src/core/csp/config.ts The experimental.csp config schema and shared types.
packages/astro/src/core/csp/common.ts Shared constants and helpers.

The user-facing config lives in packages/astro/src/core/config/schemas/base.ts (look for cspAlgorithmSchema, cspHashSchema, allowedDirectivesSchema).

Configuration

import { defineConfig } from 'astro/config';

export default defineConfig({
  experimental: {
    csp: {
      algorithm: 'sha256',
      directives: ['report-uri /csp-report'],
      styleDirective: { resources: ['https://fonts.bunny.net'] },
      scriptDirective: { strictDynamic: true },
    },
  },
});

The schema understands distinct directives for script-src, style-src, img-src, etc. and the algorithm choices (sha256, sha384, sha512).

How it works

graph LR
    A[RenderContext starts] --> B[Generate nonce]
    B --> C[Render page]
    C --> D[Collect inline script hashes]
    C --> E[Collect inline style hashes]
    D --> F[Compose CSP string]
    E --> F
    G[experimental.csp config] --> F
    F --> H{Header or meta?}
    H --> I[Set Content-Security-Policy response header]
    H --> J[Inject <meta http-equiv> into <head>]

Astro automatically includes hashes for the framework's own inline scripts (the hydration shim loaders) so users don't have to enumerate them.

Server islands and CSP

Server islands fetch additional HTML at runtime. Their inline scripts and styles must also pass CSP. The CSP runtime treats per-island responses as part of the parent page's CSP context, generating hashes server-side and merging them into the parent's policy. This is one of the harder integration points in the framework.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Content Security Policy – Astro wiki | Factory