Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Runtime Basics

Environment Variables and Configuration

Read environment variables in Bun with Bun.env and process.env, rely on automatic .env loading, choose files per environment, expand variables, validate config and keep secrets safe.

Programs need settings that change between your laptop, a test run and production: a database address, an API key, a port. The standard way to supply them is environment variables. Bun makes this pleasant: it reads .env files by itself, so you do not need the dotenv package, and it exposes variables through both process.env (Node-compatible) and Bun.env. This lesson covers reading them, the file-loading rules, expansion, validation and secret hygiene.

Reading variables

TypeScript
console.log(Bun.env.HOME);          // Bun's way
console.log(process.env.HOME);      // Node-compatible, same values
console.log(import.meta.env.HOME);  // also the same object

All three refer to the same data. Values are always strings or undefined. A missing variable is undefined, not an empty string, and numbers must be converted:

TypeScript
const port = Number(Bun.env.PORT ?? 3000);
const debug = Bun.env.DEBUG === "true";

A very common bug is if (process.env.DEBUG) when the value is the string "false": any non-empty string is truthy. Compare against the exact string you expect.

Automatic .env loading

When you start Bun from a folder, it looks for these files in the working directory and loads them before your code runs, in this order (later files win):

  1. .env
  2. .env.production, .env.development or .env.test, chosen by NODE_ENV
  3. .env.local (not loaded when NODE_ENV is test)

Actually-set variables in the real shell always take priority over files, so PORT=8080 bun run server.ts beats whatever .env says. Here is an example project:

TEXT
# .env
APP_NAME=Tutorial API
PORT=3000
DATABASE_URL=sqlite://dev.db

# .env.production
PORT=8080
DATABASE_URL=postgres://db.internal/app
TypeScript
// server.ts
console.log(`${Bun.env.APP_NAME} on port ${Bun.env.PORT}`);
Terminal
bun server.ts                      # Tutorial API on port 3000
NODE_ENV=production bun server.ts  # Tutorial API on port 8080

bun test sets NODE_ENV=test, so a .env.test file is the natural home for test database settings.

Choosing files explicitly

Terminal
bun --env-file=.env.staging run server.ts
bun --env-file=.env --env-file=.env.local run server.ts

Each --env-file is loaded in order, so later files override earlier ones. Put the flag in a package.json script to make an environment one short command. The flags around loading have grown over releases, so run bun --help to see what your version offers.

Syntax of .env files

The file format is deliberately simple:

TEXT
# A comment
PLAIN=value
QUOTED="value with spaces"
SINGLE='no $expansion here'
MULTILINE="line one
line two"
EMPTY=
  • Lines starting with # are comments.
  • Double quotes allow escapes such as \n; single quotes keep text literal.
  • Quotes may span lines for multi-line values (a private key, for example).
  • There is no spacing around =.

Variable expansion

A value can reference earlier variables with $NAME or ${NAME}:

TEXT
HOST=localhost
PORT=3000
URL=http://${HOST}:${PORT}/api
SECRET="costs $5"      # use single quotes or escape the dollar for a literal $

Use this to avoid repeating pieces of a connection string. Unknown names expand to an empty string, so check the result when a value looks wrong.

Practising the parsing in Node

Node 24 can parse the same file format with util.parseEnv. The stand-in shows how a .env file turns into an object of strings:

Node.js Stand-in: parse .env text (runs on Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Config module pattern

Reading Bun.env all over your code makes typos easy and hides what the app needs. Collect it in one file that validates at start-up and exports a typed object:

TypeScript
// src/config.ts
function required(name: string): string {
  const value = Bun.env[name];
  if (!value) {
    throw new Error(`Missing environment variable: ${name}`);
  }
  return value;
}

export const config = {
  appName: Bun.env.APP_NAME ?? "app",
  port: Number(Bun.env.PORT ?? 3000),
  databaseUrl: required("DATABASE_URL"),
  isProduction: Bun.env.NODE_ENV === "production",
} as const;

Now import { config } from "./config" gives auto-completion, and a missing setting fails at start, not on the first request three hours later. Libraries like Zod can replace the hand-written checks with a schema.

Node.js Stand-in: a config loader that fails fast (runs on Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Built-in variables

Bun and your OS set many variables. Ones worth knowing:

Variable Effect
NODE_ENV development by default for bun run; test under bun test; set production for deploys.
BUN_CONFIG_* Several settings (for example, disabling telemetry or the update check) have an env equivalent.
PORT Bun.serve uses it as the default port when you do not pass one.
TZ Timezone used by Date.
NO_COLOR / FORCE_COLOR Disable or force coloured terminal output.
BUN_INSTALL Where Bun was installed (~/.bun).

Check the release notes for names that may have changed in newer versions.

Secrets: what never to do

  • Never commit .env files that hold real secrets. Add .env* (except an example) to .gitignore, and commit a .env.example listing the names with fake values.
  • Never print secrets in logs or error messages.
  • Never embed them in client-side code. When you bundle for the browser (see the build lesson), only variables you explicitly expose reach the output, and anything exposed is public.
  • Prefer your host's secret store in production, injected as real environment variables.

Setting variables for one command

Terminal
# macOS, Linux
PORT=4000 bun server.ts

# Windows PowerShell
$env:PORT = "4000"; bun server.ts

Package scripts in package.json are run by Bun's shell, which supports the leading NAME=value form on all platforms:

JSON
{
  "scripts": {
    "dev": "PORT=4000 bun --watch src/index.ts",
    "prod": "NODE_ENV=production bun src/index.ts"
  }
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does a value read from Bun.env always have?

    Environment variables are strings; a missing one is undefined. Convert numbers and booleans yourself.
  2. 2. Which of these wins when the same variable is set in the shell and in .env?

    Real environment variables take priority over values loaded from .env files.
  3. 3. Which .env file is read when NODE_ENV=production?

    Bun loads .env first and then .env.production, so production values override the general ones.
  4. 4. Why create a config module that validates variables at start-up?

    Failing fast with a clear message is easier to debug than an undefined value used later.

Summary

  • Read variables with Bun.env, process.env or import.meta.env; all point to the same strings.
  • Bun auto-loads .env, then .env.{production,development,test}, then .env.local; shell variables win.
  • --env-file selects files explicitly; ${NAME} expansion is supported inside .env.
  • Convert types yourself and beware that the string "false" is truthy.
  • Validate in one config module, keep secrets out of git and out of client bundles.

Next: Web APIs and Built-in Utilities