#how to setup env at astro
5 messages · Page 1 of 1 (latest)
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 isdevelopmentwhen runningastro devandproductionwhen runningastro build.import.meta.env.PROD:trueif your site is running in production;falseotherwise.import.meta.env.DEV:trueif your site is running in development;falseotherwise. Always the opposite ofimport.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 thesiteoption specified in your project’sastro.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;
For more information, you can refer to the Astro documentation on environment variables (https://docs.astro.build/en/guides/environment-variables/).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@supple maple kapa.ai is still learning and improving, please let us know how it did by reacting below