Using environment variables
Astro uses Vite for environment variables, and allows you to use any of its methods to get and set environment variables.
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.
See the official Environment Variables example for best practices.
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:
production): the mode your site is running in. This is
string): the base url your site is being served from. This is determined by the
boolean): whether your site is running in production.
boolean): whether your site is running in development (always the opposite of
siteoption specified in your project’s
Setting environment variablesSection titled Setting environment variables
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.
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: