How to Use Environment Variables in Bun JS

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:

  1. .env
  2. .env.production, .env.development, .env.test
  3. .env.local

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:

SITE=iamdev
SERVER=$SITE.net/login
process.env.SERVER; // outputs "iamdev.net/login"

How to Access 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.

Leave a Comment