Astro security starts from a strong default: a static Astro site is a folder of HTML, CSS and assets with no server code to attack. The checklist that matters covers what you add: secrets kept out of client code with astro:env, a Content Security Policy and security headers at the host, no unsanitized user content in set:html, validated input on every action or endpoint, secure cookies, and dependencies kept up to date.
This checklist has 20 items in five groups. The first two groups apply to every site; the rest apply once you render routes on demand.
Key Takeaways
- Declare secrets in the
astro:envschema ascontext: 'server', access: 'secret'. Never prefix them withPUBLIC_.- Set security headers at your host; Astro’s
security.cspoption can generate hashes for its own scripts and styles.set:htmlbypasses escaping. Only pass it trusted or sanitized HTML.- Validate every input on the server, for example with Zod schemas in Astro Actions.
- Keep
security.checkOriginon, and setimage.remotePatternsnarrowly.
Secrets and configuration (every site)
1. Keep secrets out of client code
Anything prefixed with PUBLIC_ or imported into a <script> or island ends up in JavaScript anyone can read. Use the typed env schema so Astro enforces the boundary:
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
export default defineConfig({
env: {
schema: {
STRIPE_SECRET_KEY: envField.string({ context: 'server', access: 'secret' }),
PUBLIC_PLAUSIBLE_DOMAIN: envField.string({ context: 'client', access: 'public', optional: true }),
},
},
});
// src/pages/api/checkout.ts
import { STRIPE_SECRET_KEY } from 'astro:env/server';
Server secrets can only be imported from astro:env/server, which can’t be used in client code. The environment variables guide covers validation and defaults.
2. Keep .env files out of Git
Check .gitignore contains .env and .env.* (but not .env.example). If a secret was ever committed, rotate it; removing the file doesn’t remove it from history.
3. Don’t build secrets into static pages
On a static site, anything a page reads at build time and renders is public. An API key used in frontmatter is safe only if the page doesn’t print it. Review what your build fetches and outputs.
4. Never expose the dev or preview server
astro dev and astro preview are for local use. Don’t run them as a production server or expose them with --host on an untrusted network. Deploy the dist/ output, or the adapter’s server entry for on-demand sites.
Headers and browser protections (every site)
5. Set security headers at the host
On Cloudflare Pages and Netlify, a public/_headers file applies headers to every response:
# public/_headers
/*
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
X-Frame-Options: DENY
Vercel uses a vercel.json headers block for the same thing. The headers file tip and security headers tip have host-specific examples.
6. Add a Content Security Policy
A CSP limits where scripts, styles and other resources can load from, which blunts cross-site scripting. Astro can generate one for you:
// astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
security: {
csp: true,
},
});
With csp enabled, Astro adds a <meta http-equiv="content-security-policy"> with hashes for the scripts and styles it bundles. External scripts and styles aren’t covered automatically; add their hashes or sources through the csp object options. Test thoroughly in preview before deploying, since a strict policy will block anything you forgot. The CSP explainer and the official configuration reference list the options.
7. Load third-party scripts carefully
Every third-party script runs with full access to your page. Keep the list short, load from the vendor’s official URL, and use integrity hashes for versioned files from CDNs. Analytics and chat widgets are the usual suspects; review them once a quarter.
8. Use set:html only with trusted content
set:html inserts raw HTML without escaping. That’s fine for JSON-LD you build yourself or Markdown you rendered from your own repo:
<script type="application/ld+json" set:html={JSON.stringify(schema)} />
It’s dangerous with anything a user or third-party API controls. Sanitize that HTML first with a library such as sanitize-html or DOMPurify, or render it as text with normal {expression} syntax, which Astro escapes automatically.
Forms, actions and endpoints (server routes)
9. Validate every input on the server
Client-side validation is for convenience; the server must re-check. Astro Actions validate input with Zod before your handler runs:
// src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro/zod';
export const server = {
contact: defineAction({
accept: 'form',
input: z.object({
name: z.string().min(1).max(100),
email: z.email(),
message: z.string().min(10).max(5000),
}),
handler: async (input) => {
// input is typed and validated here
return { ok: true };
},
}),
};
For plain endpoints, parse request.formData() or request.json() through a Zod schema with safeParse() and return 400 on failure. The Astro Actions guide covers error handling.
10. Keep checkOrigin on
security.checkOrigin defaults to true for on-demand pages. It rejects form submissions (POST, PUT, PATCH, DELETE with form content types) whose Origin header doesn’t match your site, which blocks cross-site request forgery for forms. Don’t disable it unless you have another CSRF defense.
11. Limit request body sizes
Astro caps action bodies with security.actionBodySizeLimit, 1 MB by default. Lower it if your forms are small, and validate file uploads for type and size separately.
12. Rate-limit sensitive routes
Login, signup, password reset and contact endpoints attract bots. Rate-limit by IP in middleware or at the edge (Cloudflare and other hosts offer rules), and add a challenge such as Cloudflare Turnstile on public forms. The rate limiting tip has a middleware example.
13. Return generic errors
Don’t send stack traces or database messages to the browser. Log details on the server and respond with a short, generic message and the right status code.
Sessions, cookies and auth (server routes)
14. Set secure cookie options
// inside an endpoint, action or middleware
context.cookies.set('prefs', value, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 30,
});
httpOnly hides the cookie from JavaScript, secure keeps it on HTTPS, and sameSite: 'lax' limits cross-site sending.
15. Regenerate sessions on login
With Astro’s session API, call await Astro.session.regenerate() (or context.session in endpoints) after a successful login to prevent session fixation, and destroy() on logout. Store only IDs and small values in sessions, not full user records.
16. Protect routes in middleware, not just in the UI
Hiding a link doesn’t protect a page. Check the user in src/middleware.ts and redirect or return 401 for protected paths. The authentication options guide shows the pattern for each library.
17. Restrict forwarded host headers
Behind a proxy, Astro reads X-Forwarded-Host only if it matches security.allowedDomains. Set it to your real domains so a spoofed header can’t change the URLs Astro generates.
Images, dependencies and operations
18. Allow only the remote images you use
The image optimization endpoint will fetch remote images from domains you allow. Keep the list tight:
// astro.config.mjs (excerpt)
image: {
remotePatterns: [{ protocol: 'https', hostname: 'images.example-cms.com' }],
},
Wildcards for every host turn your site into a free image proxy.
19. Keep dependencies current
Run npm audit and enable Dependabot or Renovate on the repository. Remove integrations you no longer use. Upgrade Astro regularly; security fixes land in patch releases.
20. Use HTTPS and a custom domain correctly
All major static hosts give free TLS. Redirect HTTP to HTTPS, add HSTS once you’re sure (item 5), and verify DNS records after any domain change. The custom domains docs cover the setup.
Static vs on-demand: what applies
| Area | Static site | On-demand routes |
|---|---|---|
Secrets, .env, build output |
yes | yes |
Headers, CSP, third-party scripts, set:html |
yes | yes |
Input validation, checkOrigin, rate limits |
only for third-party form services | yes |
| Cookies, sessions, auth | rarely | yes |
| Remote image patterns, dependencies | yes | yes |
Static sites, which is how every Komal Astro theme builds by default, skip the whole server section: there’s no server, database or auth layer to patch. Adding on-demand routes later is fine; just come back to items 9 to 17 when you do.
FAQ
Is Astro secure?
Astro’s default static output is very secure, because there’s no server-side code running in production, only files. Risk comes from what you add: secrets in client code, unsanitized HTML, third-party scripts and server routes without validation. This checklist covers each.
How do I add a Content Security Policy in Astro?
Set security: { csp: true } in astro.config.mjs. Astro then emits a CSP meta tag with hashes for its own scripts and styles. Add hashes or allowed sources for external resources through the csp options, and test in astro preview before deploying.
How do I hide API keys in Astro?
Declare them in the env.schema of astro.config.mjs with context: 'server' and access: 'secret', and import them only from astro:env/server in server code. Never use the PUBLIC_ prefix for secrets, and never print them into a static page.
Does Astro protect against CSRF?
For on-demand routes, yes: security.checkOrigin, enabled by default, rejects form submissions whose Origin header doesn’t match your site. For JSON APIs or other content types, add your own checks, such as tokens or SameSite cookies.
Is set:html safe in Astro?
Only with trusted content. set:html inserts HTML without escaping, so passing user input or third-party HTML can lead to cross-site scripting. Sanitize untrusted HTML first, or use normal {expression} output, which Astro escapes.