withastro/astro
Environment variables
astro:env is the typed environment-variable virtual module. Authors declare a schema in astro.config.mjs and read variables through validated, typed accessors instead of import.meta.env.
Purpose
- Catch missing or misnamed env vars at build time.
- Make it explicit which variables are available on the server vs the client.
- Prevent accidental leaks of server-only secrets to the client bundle.
Key files
| File | Purpose |
|---|---|
packages/astro/src/env/schema.ts |
The defineSchema helper and primitive validators (envField.string(), etc.). |
packages/astro/src/env/runtime.ts |
Public astro:env/server, astro:env/client runtimes. |
packages/astro/src/env/setup.ts |
Build-time setup (loaded by Vite plugin). |
packages/astro/src/env/ |
Vite plugin and the rest of the supporting code. |
The package exports astro/env, astro/env/runtime, astro/env/setup for users authoring integrations on top.
Configuration
import { defineConfig, envField } from 'astro/config';
export default defineConfig({
env: {
schema: {
DATABASE_URL: envField.string({ context: 'server', access: 'secret' }),
PUBLIC_API_BASE: envField.string({ context: 'client', access: 'public' }),
RATE_LIMIT: envField.number({
context: 'server',
access: 'public',
default: 60,
}),
},
},
});context chooses whether the variable is exposed to the server or to the client; access chooses public vs secret. Secrets never reach the client bundle.
Reading
// In a server file
// In a client file
import { PUBLIC_API_BASE } from 'astro:env/client';
import { DATABASE_URL, RATE_LIMIT } from 'astro:env/server';Importing a server field from a client file is a build error.
How it works
graph TD
A[astro.config env.schema] --> B[Vite plugin generates astro:env modules]
B --> C[astro:env/server]
B --> D[astro:env/client]
C --> E[Validates process.env at build/start]
D --> F[Inlined values at build]
G[Server code import] --> C
H[Client code import] --> D
H -.error.-> CValidation happens at module-load time, not at import-site. A missing required variable throws an AstroError early (with a hint pointing to the schema) rather than a ReferenceError deep in user code.
Related pages
- features / sessions —
ASTRO_KEYis a common env var. - systems / build pipeline — env values are baked into the static build.
- reference / configuration
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.