🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro CSP: Content Security Policy with security.csp

Set up an Astro CSP with security.csp: automatic script and style hashes, extra directives, third-party sources, the per-page Astro.csp API and known limits.

#Astro#Astro CSP#Security#Content Security Policy#Headers

Astro has built-in Content Security Policy support: set security: { csp: true } in astro.config.mjs, and Astro hashes every script and style it bundles and writes a matching script-src and style-src policy for each page. Prerendered pages get the policy as a <meta http-equiv="content-security-policy"> tag; on-demand pages get a Content-Security-Policy response header. The feature has been stable since Astro 6.0.

This guide shows the config, how to allow third-party scripts and styles, how to change the policy per page, and what doesn’t work with an Astro CSP yet.

Key Takeaways

  • security.csp: true generates SHA-256 hashes for Astro’s own scripts and styles, so you don’t need 'unsafe-inline'.
  • Add other directives (default-src, img-src, connect-src) with csp.directives.
  • Allow external hosts with scriptDirective.resources and styleDirective.resources; include 'self' yourself.
  • Astro.csp adds directives, hashes and sources for a single route at render time.
  • CSP is not applied in astro dev. Test with astro build and astro preview. <ClientRouter /> and Shiki’s inline styles are not supported.

Why a CSP matters on an Astro site

A Content Security Policy tells the browser which sources a page may load scripts, styles, images and connections from. If an attacker manages to inject a <script> tag through a comment field, a CMS entry or a compromised dependency, the browser refuses to run it because it isn’t on the list. MDN’s CSP guide covers the directives in depth.

The hard part of CSP has always been inline code. Astro inlines small scripts and styles, and its islands use inline bootstrap code. A strict policy blocks all of that unless you either allow 'unsafe-inline' (which defeats most of the point) or list a hash for every inline block. Astro’s CSP feature does the hashing at build time, so you get the strict version without maintaining hashes by hand.

Turn on CSP in astro.config.mjs

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  security: {
    csp: true,
  },
});

Build the site and look at any page’s <head>. You’ll see something like this:

<!-- dist/index.html -->
<meta
  http-equiv="content-security-policy"
  content="script-src 'self' 'sha256-...'; style-src 'self' 'sha256-...';"
>

Astro computes hashes per page, so a page that ships no island only lists the styles it actually uses. The default algorithm is SHA-256; set csp: { algorithm: 'SHA-384' } or 'SHA-512' if your security policy asks for a stronger hash.

Meta tag or response header

Where the policy ends up depends on how the route renders:

Route type Where Astro puts the policy
Prerendered (static) page <meta http-equiv="content-security-policy"> in <head>
On-demand page (prerender = false) Content-Security-Policy response header
Static page with an adapter that supports static headers Passed to the adapter, which can write a host headers file

The meta tag covers most directives, but a few, such as frame-ancestors and report-uri, are ignored by browsers when delivered through <meta>. If you need those on a static site, set them as a response header at your host (a _headers file on Cloudflare Pages or Netlify, vercel.json on Vercel) alongside Astro’s meta tag. The Cloudflare Pages deploy docs show where that file lives in a theme project.

Add more directives

Astro only writes script-src and style-src by default. Everything else goes in directives:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  security: {
    csp: {
      directives: [
        "default-src 'self'",
        "img-src 'self' data: https://images.example-cdn.com",
        "font-src 'self'",
        "connect-src 'self' https://plausible.io",
        "form-action 'self' https://formspree.io",
        "base-uri 'self'",
        "object-src 'none'",
      ],
    },
  },
});

These directives are added to every page. Start with default-src 'self' and open up only what the build actually needs. If you self-host fonts (the self-hosted fonts guide covers Astro’s Fonts API), font-src 'self' is enough.

Allow third-party scripts and styles

External scripts can’t be hashed by Astro at build time, so they need a source entry. Use scriptDirective.resources and styleDirective.resources. These replace Astro’s default sources, so add 'self' back explicitly:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  security: {
    csp: {
      scriptDirective: {
        resources: ["'self'", 'https://plausible.io'],
      },
      styleDirective: {
        resources: ["'self'", 'https://fonts.googleapis.com'],
      },
    },
  },
});

If you load a specific external file and prefer a hash over a whole host, add it with scriptDirective.hashes or styleDirective.hashes. Hashes must start with sha256-, sha384- or sha512-, or Astro fails config validation.

For scripts that inject other scripts (tag managers, some embed widgets), scriptDirective.strictDynamic: true adds the 'strict-dynamic' keyword. A trusted, hashed script can then load further scripts without each one being listed. Weigh that carefully: it trusts whatever the loader pulls in.

Inline style attributes and the kind option

Since Astro 7.1, hash and resource entries can be objects with a kind that targets the more specific directives: "element" for script-src-elem and style-src-elem, "attribute" for script-src-attr and style-src-attr. The common use is inline style="..." attributes, which hashes can’t cover. Code that uses define:vars produces them, for example:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  security: {
    csp: {
      styleDirective: {
        resources: [
          "'self'",
          { resource: "'unsafe-inline'", kind: 'attribute' },
        ],
      },
    },
  },
});

This allows inline style attributes through style-src-attr while <style> elements stay hash-checked. One caution from Astro’s reference: if you put 'unsafe-inline' in a directive without a kind, Astro stops emitting hashes on that directive, because browsers ignore 'unsafe-inline' when hashes are present. That drops the directive to 'unsafe-inline' strength.

Change the policy for one page with Astro.csp

Some pages need more than the global policy: a page with an embedded map, a checkout with a payment iframe. On on-demand and prerendered routes, Astro.csp (and context.csp in middleware) adds to the policy for that route only:

---
// src/pages/contact.astro
Astro.csp.insertDirective("frame-src https://www.google.com");
Astro.csp.insertScriptResource('https://www.google.com');
---
<iframe
  src="https://www.google.com/maps/embed?pb=..."
  title="Office location"
  loading="lazy"
></iframe>

The runtime API has insertDirective(), insertScriptResource(), insertScriptHash(), insertStyleResource() and insertStyleHash(). Astro merges and deduplicates what you insert with the config, so you can keep the global policy tight and widen it only where needed.

Limits to know before you enable it

  • Not active in dev. The Vite dev server injects scripts in ways that can’t be hashed, so CSP is skipped in astro dev. Run astro build and astro preview to test. Add a preview check to your launch checklist.
  • <ClientRouter /> isn’t supported. If you use Astro’s client-side router, CSP and view transitions conflict. The browser’s native cross-document view transitions work with CSP; see native view transitions vs ClientRouter.
  • Shiki inline styles. Shiki writes inline style attributes on code tokens. Either allow inline style attributes with the kind: 'attribute' pattern above or use the <Prism /> component, which Astro’s docs suggest for CSP projects.
  • External scripts and styles need explicit entries. Analytics, chat widgets and embeds all need a source or hash.

Komal Nakrani Astro themes are static builds with little client JavaScript, so a policy for them is usually short: turn on csp: true, add directives for images and fonts, and list your analytics host.

Test and roll out safely

  1. Build and preview locally, then open the browser console. Blocked resources show up as CSP violation messages naming the directive.
  2. Fix each violation by adding a source, a hash or a per-page directive.
  3. For a cautious rollout on a live site, send the policy first as a Content-Security-Policy-Report-Only header at your host. Browsers report violations without blocking anything.
  4. Once the reports are clean, rely on Astro’s enforced policy.

The Astro configuration reference lists every security.csp option with its version.

FAQ

Does Astro support Content Security Policy?

Yes. Since Astro 6.0, security.csp in astro.config.mjs generates hashes for Astro’s scripts and styles and writes a script-src and style-src policy for every page. You can add directives, external sources and extra hashes in the same config.

Why does my Astro CSP not work in dev mode?

Astro skips CSP in astro dev because the Vite dev server injects scripts that can’t be hashed ahead of time. Run astro build followed by astro preview to see the real policy and test violations.

How do I allow Google Analytics or another external script with Astro CSP?

Add the script’s host to security.csp.scriptDirective.resources, together with 'self', because setting resources replaces Astro’s defaults. Add connect-src and img-src entries in directives if the script sends beacons or loads pixels.

Can I use view transitions with an Astro CSP?

Not with <ClientRouter />, which isn’t supported when CSP is enabled. Native cross-document view transitions, enabled with the @view-transition CSS rule, work with a CSP because they don’t need extra scripts.

Does Astro send CSP as a header or a meta tag?

Prerendered pages get a <meta http-equiv="content-security-policy"> tag. On-demand pages get a Content-Security-Policy header. Adapters that support static headers can receive the policy for static pages and write it to a host headers file.