#how to setup env at astro

5 messages · Page 1 of 1 (latest)

supple maple
#

how to setup env at astro

modest falconBOT
#

Hi @supple maple. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To set up environment variables in Astro, you need to create a .env file in the root of your project and define your variables there. Here's a general example:

VARIABLE_NAME=YOUR_VALUE

You can then use these variables in your project. If you want to have IntelliSense for your environment variables, you can create a env.d.ts file in the src/ directory and configure ImportMetaEnv like this:

interface ImportMetaEnv {  
  readonly VARIABLE_NAME: string;
}

Astro uses Vite’s built-in support for environment variables, which are statically replaced at build time. 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.

For example, if you have the following in your .env file:

SECRET_PASSWORD=password123
PUBLIC_ANYBODY=there

PUBLIC_ANYBODY will be available in server or client code, while SECRET_PASSWORD will be server-side only.

Astro also includes a few environment variables out-of-the-box:

  • import.meta.env.MODE: The mode your site is running in. This is development when running astro dev and production when running astro build.
  • import.meta.env.PROD: true if your site is running in production; false otherwise.
  • import.meta.env.DEV: true if your site is running in development; false otherwise. Always the opposite of import.meta.env.PROD.
  • import.meta.env.BASE_URL: The base url your site is being served from.
  • import.meta.env.SITE: This is set to the site option specified in your project’s astro.config.
  • import.meta.env.ASSETS_PREFIX: The prefix for Astro-generated asset links.

You can use them like any other environment variable:

const isProd = import.meta.env.PROD;
const isDev = import.meta.env.DEV;
#

@supple maple kapa.ai is still learning and improving, please let us know how it did by reacting below