How to read environment variables in astro.config.mjs?
- Posted on
- Authors
- Name
- ansidev
- @ansidev
Problem
You want to read environment variables from env file (ex. .env) in astro.config.mjs for development purposes.
However, according to the official document, Astro does not support it official and the only way.
You can read about it here.
Solution
In this article, I will guide you how to solve this issue.
Requirement:
- I have two sites in two languages: English and Vietnamese.
- Each site will display different region.
- English: Region =
US. - Vietnamese: Region =
VN.
- English: Region =
Steps:
Create a new Astro project
pnpm create astro@latestpnpm create astro@latestCreate
.env.en.local.VITE_REGION=USVITE_REGION=USCreate
.env.vi.local.VITE_REGION=VNVITE_REGION=VNInstall dependencies
pnpm add -D dotenv cross-envpnpm add -D dotenv cross-envAdd two scripts to
package.json.{ "scripts": { "dev:en": "cross-env SITE_LANG=en astro dev", "dev:vi": "cross-env SITE_LANG=vi astro dev" // other scripts } }{ "scripts": { "dev:en": "cross-env SITE_LANG=en astro dev", "dev:vi": "cross-env SITE_LANG=vi astro dev" // other scripts } }Update
astro.config.mjsimport dotenv from 'dotenv' const lang = process.env.SITE_LANG const envPath = `.env.${lang}.local` dotenv.config({ path: envPath })import dotenv from 'dotenv' const lang = process.env.SITE_LANG const envPath = `.env.${lang}.local` dotenv.config({ path: envPath })Now, you can read environment variables from env file anywhere in Astro app.
const region = import.meta.env.VITE_REGIONconst region = import.meta.env.VITE_REGION
You can checkout the demo source code here.