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@latest
pnpm create astro@latest
Create
.env.en.local
.VITE_REGION=US
VITE_REGION=US
Create
.env.vi.local
.VITE_REGION=VN
VITE_REGION=VN
Install dependencies
pnpm add -D dotenv cross-env
pnpm add -D dotenv cross-env
Add 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.mjs
import 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_REGION
const region = import.meta.env.VITE_REGION
You can checkout the demo source code here.