An Astro env schema is the env.schema block in astro.config.mjs, where each variable is declared with envField as a string, number, boolean or enum, plus a context (client or server) and an access level (public or secret). Astro validates the values, generates types, and decides what ends up in which bundle. Public values are written into the build. Secrets are read at runtime.
That split is what catches people. Two variables declared side by side in the same schema can behave completely differently after deploy, and the only thing deciding it is the access field.
How do you define an Astro env schema?
The environment variables guide covers the setup, and the envField reference lists the validation options. Both arrived in [email protected]. Here is a schema for a site that talks to a CMS and a payment API:
// astro.config.mjs
import { defineConfig, envField } from "astro/config";
export default defineConfig({
env: {
validateSecrets: true,
schema: {
PUBLIC_SITE_NAME: envField.string({
context: "client",
access: "public",
default: "Example Shop",
}),
CMS_URL: envField.string({
context: "server",
access: "public",
url: true,
startsWith: "https://",
}),
CMS_PAGE_SIZE: envField.number({
context: "server",
access: "public",
default: 25,
int: true,
min: 1,
max: 100,
}),
LOG_LEVEL: envField.enum({
context: "server",
access: "public",
values: ["debug", "info", "error"],
default: "info",
}),
PAYMENT_API_KEY: envField.string({
context: "server",
access: "secret",
}),
},
},
});
Then import from the matching virtual module:
// src/pages/api/checkout.ts
import type { APIRoute } from "astro";
import { CMS_URL, PAYMENT_API_KEY } from "astro:env/server";
export const prerender = false;
export const POST: APIRoute = async () => {
const res = await fetch(`${CMS_URL}/orders`, {
method: "POST",
headers: { Authorization: `Bearer ${PAYMENT_API_KEY}` },
});
return new Response(null, { status: res.status });
};
Types are generated when you run astro dev or astro build, and astro sync generates them on their own. CMS_PAGE_SIZE comes through as a number, and LOG_LEVEL as the union 'debug' | 'info' | 'error', so a typo fails in the editor rather than in production.
There is no context: "client" with access: "secret". The docs say the combination cannot be configured, because there is no safe way to send a secret to the browser.
Which Astro env variables are read at runtime?
Only the secrets.
The docs say public client variables “end up in both your final client and server bundles”, public server variables end up in the server bundle, and secret server variables “are not part of your final bundle”. The source shows what that means. We read the [email protected] package, and its env plugin turns each validated public variable into a constant in the generated module:
export const CMS_URL = "https://cms.example.com";
export const CMS_PAGE_SIZE = 25;
Secrets get a call to an internal lookup instead, which asks the adapter for the value when the server module loads.
So if you change CMS_URL in your hosting dashboard and redeploy the same build artifact, nothing happens. The old URL is a string literal in the bundle. A public variable needs a rebuild. A secret only needs a restart, or a new deploy of the same build.
Prerendered pages are a separate case. A page with no prerender = false is rendered at build time, so any secret it reads is the value that existed in the build environment, and that value is baked into the HTML. Keep pages that read secrets on demand.
Why does the build fail with “is missing”?
Validation errors come back as EnvInvalidVariables, with a list underneath:
The following environment variables defined in `env.schema` are invalid:
- PAYMENT_API_KEY is missing
- CMS_PAGE_SIZE's type is invalid, expected: number
Three behaviours explain most of these.
First, an empty string counts as missing. PAYMENT_API_KEY= in a .env file is treated the same as not setting it, so a placeholder line does not satisfy a required field.
Second, secrets are validated more often than you might expect. Without validateSecrets, public variables are checked at startup and secrets are checked when the server module loads. The guide warns that all secrets are validated “whenever anything is imported from the astro:env/server module”, even ones that file never imports. If a prerendered page imports CMS_URL from astro:env/server, the build needs every secret in the schema to be present. The docs suggest passing dummy values during the build. We prefer setting validateSecrets: true and giving CI the real secrets, so a missing key fails the pipeline instead of the first request.
Third, the parsers are stricter in some places than you expect, and looser in others.
Booleans, numbers and URLs
A boolean must be the exact string true or false. 1, yes and TRUE all fail with a type error. If your platform templates write 1, change them or use an enum.
Numbers go through Number.parseFloat, which reads a leading number and stops. 3000ms parses as 3000 and passes. Add int: true and a min/max range if a stray suffix would matter.
The url: true check uses URL.canParse, and URL.canParse("localhost:3000") returns true, because localhost: reads as a URL scheme. Pair url: true with startsWith: "https://" when you mean a web address.
Where can you not use astro:env?
astro:env is a virtual module, so it only exists inside the Astro build: pages, endpoints, middleware, components and the modules they import. It does not work in astro.config.mjs or in standalone scripts. Use process.env there, or Vite’s loadEnv helper if you need .env files loaded in the config.
Importing astro:env/server into a client <script> fails with ServerOnlyModule: The "astro:env/server" module is only available server-side. Move the value to a client/public field, or fetch it from an endpoint.
On Cloudflare, the adapter guide says variables and secrets are compatible with astro:env/server, so a secret set with npx wrangler secret put (or a .dev.vars line locally) arrives through the same import. If you have not picked a Cloudflare target yet, our Cloudflare Pages vs Workers comparison explains why new projects belong on Workers. For keys you cannot list ahead of time, getSecret("KEY") from astro:env/server returns the raw value as string | undefined, with no validation.
One more guard. If you set vite.envPrefix to a prefix that a secret’s name starts with, Vite would expose that secret through import.meta.env in client code. The 7.4.12 package refuses to build in that case and throws EnvPrefixConflictsWithSecret. Rename the secret or drop the prefix.
Should you move off import.meta.env?
For anything a server reads, yes. Since Astro 6, import.meta.env is always inlined and never type-coerced, as we covered in our Astro 7 upgrade notes, so import.meta.env.FEATURE_ON is the string "true" and every comparison has to know that. The schema gives you real booleans and numbers, one list of every variable the app depends on, and a failed build when one is absent.
We would put every secret in the schema as context: "server", access: "secret" and turn on validateSecrets. We would make a value public only when it is fine for it to be frozen into the build. A feature flag you want to flip without a rebuild should be a secret, even though nothing about it is confidential, because that is the only access level read at runtime. We would leave import.meta.env for Astro’s built-ins such as import.meta.env.DEV and import.meta.env.SITE.
The exception is a fully static site with no adapter. Everything is read at build time anyway, so the main gain is the type checking, and a small site with two variables may not need it.
We build and maintain Astro and TypeScript sites, including the deployment and secrets setup behind them on Cloudflare and Node hosts. If your config has grown into a pile of import.meta.env lookups, our TypeScript development work covers this kind of clean-up.