Bun JS, like all other server side tech, comes with the ability to read environment variables from files.
Environment files in your project root directory are read in this particular order:
- .env
- .env.production, .env.development, .env.test
- .env.local
Note that for item 2 bun will first read from variable NODE_ENV, to decide which one to select.
You can also manually override which file bun env should read when you start the server:
bun --env-file=.env.v1 index.ts
//you can even have multiple env files!
bun --env-file=.env.v1 --env-file=.env.test src/index.ts
Expanding (Concatenating) Environment Variables in bun
Bun will automatically concat any variables in env files, for example:
SITE=iamdev
SERVER=$SITE.net/login
process.env.SERVER; // outputs "iamdev.net/login"
How to Access bun env Environment Variables in Code
You can use the standard syntax:
process.env.VARNAME
Alternatively you can use the bun version
Bun.env.VARNAME
That’s all for the most commonly requested points on environment variables. There are a couple of other more advanced points that bun themselves document, which you can find here.