Bun JS, like all other server side tech, comes with the ability to read your environment variables.
Environment variable files are read in a particular order though:
- .env.production, .env.development, .env.test
Note that in item 2 (prod / dev / test) bun will first read the current environment variable -> NODE_ENV, to decide which one to select.
You can also manually override which file bun 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 your variables in env files, for example:
process.env.SERVER; // outputs "iamdev.net/login"
How to Access Environment Variables in Code
You can use the standard syntax:
Alternatively you can use the bun version
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.