Astro environment variables come from .env files and the host’s settings, and you read them in two ways: import.meta.env.NAME (Vite’s built-in, untyped) or the astro:env modules, which validate every variable against a schema in astro.config.mjs and give you typed imports. Variables prefixed with PUBLIC_ (or declared with context: 'client') can reach the browser; everything else stays on the server.
This guide covers both approaches in Astro 7, how secrets behave in static and on-demand builds, and how to set variables on each common host.
Key Takeaways
import.meta.envworks everywhere, but onlyPUBLIC_variables are exposed to client code.astro:envadds a schema: types, defaults, validation and a clear error when a variable is missing.astro:env/clientexports public variables;astro:env/serverexports server-only ones, including secrets.- In a static build, every value is read at build time and baked into the output.
- Secrets declared with
access: 'secret'are read at runtime on on-demand pages, so you can rotate them without rebuilding.
How Astro loads environment variables
Astro uses Vite to load variables. When you run astro dev or astro build, it reads these files from the project root, later files overriding earlier ones:
| File | Loaded when | Commit it? |
|---|---|---|
.env |
Always | Usually no |
.env.local |
Always, except in tests | No |
.env.development |
astro dev |
Optional |
.env.production |
astro build |
Optional |
Variables already set in the shell or by the hosting platform take priority over file values. That’s how production values on Netlify, Vercel or Cloudflare override whatever is in your local .env.
# .env
PUBLIC_SITE_NAME="Example Studio"
PUBLIC_ANALYTICS_ID="abc123"
CMS_API_TOKEN="sk_live_replace_me"
Add .env and .env.local to .gitignore, and commit an .env.example with the variable names and placeholder values so the next developer knows what to set.
Reading variables with import.meta.env
The simplest way is import.meta.env, which works in .astro files, endpoints, middleware and framework components:
---
// src/pages/index.astro
const siteName = import.meta.env.PUBLIC_SITE_NAME;
const token = import.meta.env.CMS_API_TOKEN;
const posts = await fetch('https://cms.example.com/posts', {
headers: { Authorization: `Bearer ${token}` },
}).then((r) => r.json());
---
<h1>{siteName}</h1>
Two rules decide what’s visible:
- In server code (the frontmatter of
.astrofiles, endpoints, middleware), every variable is available. - In client code (a
<script>tag or a component hydrated with aclient:*directive), only variables starting withPUBLIC_are replaced. A non-public variable isundefinedin the browser.
Astro also provides built-in values: import.meta.env.MODE ('development' or 'production'), DEV, PROD, BASE_URL (the configured base), SITE (the configured site) and ASSETS_PREFIX.
To get autocomplete for your own variables with import.meta.env, declare them in src/env.d.ts:
// src/env.d.ts
interface ImportMetaEnv {
readonly PUBLIC_SITE_NAME: string;
readonly CMS_API_TOKEN: string;
}
This only adds types. Nothing checks that the variable actually exists, which is the gap astro:env fills.
Type-safe Astro environment variables with astro:env
astro:env lets you declare every variable in astro.config.mjs with envField. Astro validates them when the dev server starts and during the build, generates types, and exposes them through virtual modules.
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
export default defineConfig({
env: {
schema: {
PUBLIC_SITE_NAME: envField.string({ context: 'client', access: 'public' }),
PUBLIC_ANALYTICS_ID: envField.string({ context: 'client', access: 'public', optional: true }),
CMS_URL: envField.string({ context: 'server', access: 'public', url: true }),
CMS_API_TOKEN: envField.string({ context: 'server', access: 'secret' }),
PAGE_SIZE: envField.number({ context: 'server', access: 'public', default: 12, int: true, min: 1 }),
SHOW_BETA: envField.boolean({ context: 'server', access: 'public', default: false }),
DEPLOY_TARGET: envField.enum({
context: 'server',
access: 'public',
values: ['preview', 'production'],
default: 'preview',
}),
},
},
});
Every field needs a context and an access:
| Combination | Import from | Use for |
|---|---|---|
context: 'client', access: 'public' |
astro:env/client |
Values the browser can see: analytics IDs, public API URLs |
context: 'server', access: 'public' |
astro:env/server |
Server config that isn’t sensitive: page size, feature flags |
context: 'server', access: 'secret' |
astro:env/server |
API tokens, database URLs, signing keys |
There’s no client plus secret combination, because a secret sent to the browser isn’t a secret.
The field types and their options, taken from Astro’s schema:
| Type | Options besides optional and default |
|---|---|
envField.string |
min, max, length, url, includes, startsWith, endsWith |
envField.number |
gt, min, lt, max, int |
envField.boolean |
none |
envField.enum |
values (required) |
Importing from astro:env/client and astro:env/server
Once the schema exists, import variables by name. They’re typed from the schema, so PAGE_SIZE is a number and SHOW_BETA is a boolean, with no parseInt or === 'true' checks.
---
// src/pages/blog/index.astro
import { PUBLIC_SITE_NAME } from 'astro:env/client';
import { CMS_URL, CMS_API_TOKEN, PAGE_SIZE } from 'astro:env/server';
const res = await fetch(`${CMS_URL}/posts?limit=${PAGE_SIZE}`, {
headers: { Authorization: `Bearer ${CMS_API_TOKEN}` },
});
const posts = await res.json();
---
<h1>{PUBLIC_SITE_NAME} blog</h1>
<ul>
{posts.map((post) => <li>{post.title}</li>)}
</ul>
Client variables work in browser scripts too:
---
// src/components/Analytics.astro
---
<script>
import { PUBLIC_ANALYTICS_ID } from 'astro:env/client';
if (PUBLIC_ANALYTICS_ID) {
console.log('analytics id', PUBLIC_ANALYTICS_ID);
}
</script>
If you import astro:env/server from a script or a hydrated component, the build fails instead of leaking the value. That error is the point of the module split. The module is only available server-side tip shows how to move such code back to the server.
What happens when a variable is missing or invalid
When a required variable is absent, or a value fails its constraints, Astro stops with this error:
Invalid environment variables.
The following environment variables defined in `env.schema` are invalid:
- CMS_URL is missing
That’s far better than a page that renders undefined in production. The invalid environment variables fix walks through each cause, from typos to a number field receiving text.
Secrets are only checked when they’re read, unless you ask Astro to check them at startup:
// astro.config.mjs (excerpt)
env: {
schema: { /* ... */ },
validateSecrets: true,
},
With validateSecrets: true, a missing secret fails the dev server and the build immediately, rather than at the first request that needs it.
Build-time values versus runtime secrets
How a variable is read depends on how the page is rendered.
Static pages (the default output: 'static') are rendered once during astro build. Every variable they use, secret or not, is read on the build machine and the result is written into HTML. To change a value, you rebuild. Using a secret to fetch content at build time is safe, because the token itself isn’t written to the page unless you print it.
On-demand pages (with an adapter and export const prerender = false) run on each request. Variables with access: 'secret' are read from the runtime environment through the adapter, so on Cloudflare, Netlify, Vercel or Node.js you can rotate a token in the host’s dashboard and the next request uses it. Public server and client variables are still inlined at build time.
For dynamic keys, astro:env/server also exports getSecret, which reads any variable from the runtime environment by name:
// src/pages/api/status.ts
import type { APIRoute } from 'astro';
import { getSecret } from 'astro:env/server';
export const prerender = false;
export const GET: APIRoute = () => {
const region = getSecret('DEPLOY_REGION') ?? 'unknown';
return Response.json({ region });
};
If you’re deciding which pages should be static and which on demand, the rendering mode guide helps.
Setting environment variables on your host
Each host has a settings screen for variables. Set them for the right environment (production, preview, or both) and redeploy after changing anything used at build time.
| Host | Where to set them |
|---|---|
| Cloudflare Pages / Workers | Project > Settings > Variables and Secrets |
| Netlify | Site configuration > Environment variables |
| Vercel | Project > Settings > Environment Variables |
| GitHub Pages | Repository > Settings > Secrets and variables > Actions, then pass them in the workflow’s env: |
| Node.js server | The process environment, from your process manager, container or systemd unit |
For GitHub Pages, the variables must be passed to the build step explicitly; see deploying Astro to GitHub Pages. For the others, the host injects them into both the build and the runtime. The static hosting docs list the build settings for each.
Komal themes are static and don’t require any environment variables to build, so you only add them when you connect analytics, a form service or a CMS to one of the Astro themes.
Common mistakes
- Using a non-
PUBLIC_variable in a script. It’sundefinedin the browser. Rename it with the prefix only if the value is safe to publish. - Putting a secret behind
PUBLIC_. Anything public ends up in JavaScript that anyone can read. Rotate the key if this happened. - Expecting a static page to pick up a new value. Static HTML is built once. Rebuild, or make the page on demand.
- Reading
process.envin client code. It doesn’t exist in the browser. Useimport.meta.envorastro:env/client. - Forgetting the schema after adding a variable. With
astro:env, an undeclared variable isn’t exported. Add it toenv.schemafirst.
The official reference is Astro’s environment variables guide.
FAQ
What is the difference between import.meta.env and astro:env?
import.meta.env is Vite’s object of raw string values with no validation. astro:env is Astro’s schema layer: you declare each variable once, Astro checks it at startup, converts numbers and booleans, and exports typed values from astro:env/client and astro:env/server. Both read the same .env files and host settings.
Why is my Astro environment variable undefined?
Usually one of three reasons: it’s used in client code without the PUBLIC_ prefix, the .env file isn’t in the project root, or the dev server wasn’t restarted after the file changed. On a host, check the variable is set for the environment you deployed (production or preview).
Can I use environment variables in a static Astro site?
Yes. They’re read during astro build, and the results are written into the HTML. That’s fine for API tokens used to fetch content at build time, as long as you don’t render the token itself. Changing a value requires a rebuild.
How do I keep API keys secret in Astro?
Read them only in server code: page frontmatter, endpoints, middleware or actions. With astro:env, declare them as context: 'server', access: 'secret'. Astro then refuses to bundle them into client code and, on on-demand pages, reads them from the runtime environment instead of inlining them.
Does Astro support .env.production?
Yes. astro build loads .env.production and astro dev loads .env.development, on top of .env. Host-level variables still override both.