Content Security Policy is like a bouncer for your website. It tells the browser what content is allowed to load and from where. This helps prevent a whole bunch of nasty attacks, like Cross-Site Scripting (XSS) and data injection.
Content Security Policy (CSP) should be implemented as a response header, not a request header. Here’s why:
- CSP is a security mechanism enforced by the browser on the client-side.
- The server sends the CSP directives to the browser as part of its response.
- The browser then enforces these policies when loading and executing content.
So, in the context of Astro.js and web servers in general, CSP headers should be set on the server’s responses to the client. This means that when configuring CSP, we’re always dealing with response headers.
Implementing CSP in Astro
Let’s start with a basic CSP setup for an Astro site. We’ll use the astro.config.mjs
file to add our headers.
This configuration does a few things:
default-src 'self'
: Only allows resources to be loaded from the same origin.script-src 'self' 'unsafe-inline'
: Allows scripts from the same origin and inline scripts (which Astro uses).style-src 'self' 'unsafe-inline'
: Allows styles from the same origin and inline styles.
The Astro CSP Gotcha
Astro has a unique architecture that can trip up CSP. It uses a technique called “partial hydration” where some components are static and others are interactive. This means your CSP needs to be flexible enough to allow for this hybrid approach.
Here’s a more comprehensive CSP for a typical Astro site.
This policy is more permissive but still secure. It allows for Astro’s hydration needs 'unsafe-eval'
and common use cases like loading images from HTTPS sources.
Vercel Approach
With Vercel, you can use a vercel.json
file in your project root:
This applies the CSP header to all routes on your Vercel-deployed Astro site. All you have to do with git push
to deploy your changes.
Cloudflare Approach
Cloudflare uses Page Rules to add headers. Here’s how you might set it up:
- Go to your Cloudflare dashboard
- Navigate to Rules > Page Rules
- Click on the ‘Modify Response Headers’ tab
- Click ‘Create rule’
- Click ‘Add Static Header to Response’
- Add a “CSP” Header:
- Header Name: Content-Security-Policy
- Value: Your CSP string
The advantage of Cloudflare’s approach is that you can easily update your CSP without redeploying your site.