Astro uses Vite’s built-in support for environment variables, and lets you use any of its methods to work with them.
Note that while all environment variables are available in server-side code, only environment variables prefixed with
PUBLIC_ are available in client-side code for security purposes.
In this example,
PUBLIC_ANYBODY (accessible via
import.meta.env.PUBLIC_ANYBODY) will be available in server or client code, while
SECRET_PASSWORD (accessible via
import.meta.env.SECRET_PASSWORD) will be server-side only.
Default environment variablesSection titled Default environment variables
Astro includes a few environment variables out-of-the-box:
import.meta.env.MODE: The mode your site is running in. This is
trueif your site is running in production;
trueif your site is running in development;
falseotherwise. Always the opposite of
import.meta.env.BASE_URL: The base url your site is being served from. This is determined by the
import.meta.env.SITE: This is set to the the
siteoption specified in your project’s
Setting environment variablesSection titled Setting environment variables
Section titled .env files
Environment variables can be loaded from
.env files in your project directory.
You can also attach a mode (either
development) to the filename, like
.env.development, which makes the environment variables only take effect in that mode.
Just create a
.env file in the project directory and add some variables to it.
For more on
.env files, see the Vite documentation.
Using the CLISection titled Using the CLI
You can also add environment variables as you run your project:
Getting environment variablesSection titled Getting environment variables
Instead of using
process.env, with Vite you use
import.meta.env, which uses the
import.meta feature added in ES2020.
For example, use
import.meta.env.PUBLIC_POKEAPI to get the
PUBLIC_POKEAPI environment variable.
IntelliSense for TypeScriptSection titled IntelliSense for TypeScript
By default, Astro provides type definition for
While you can define more custom env variables in
.env.[mode] files, you may want to get TypeScript IntelliSense for user-defined env variables which are prefixed with
To achieve this, you can create an
src/ and configure
ImportMetaEnv like this: