Native .env Parsing: Automatic Environment Injection Without dotenv Packages
- Last updated
- Prerequisites:
- Environment variables (`process.env`)
- dotenv npm package
- bun
- dotenv
- env
- configuration
- performance
- process-env
Read at your depth
The practical view
Bun automatically loads environment variables from `.env` files into `process.env` and `import.meta.env` at startup. You do not need to install `dotenv` or write `require('dotenv').config()`. It loads files in a defined priority order: `.env.local` -> `.env.production` (or `.env.development`) -> `.env`.
The same idea in other frameworks
`require('dotenv').config()` or `node --env-file=.env` (Node 20+).`Deno.env.get('KEY')` with `--env` flag.Automatic `.env` loading into `process.env` and `import.meta.env`.`import.meta.env.VITE_KEY` (client build inlining).Legacy vs modern
Node.js dotenv Boilerplate vs Bun Automatic Injection
Node requires importing dotenv at the top of entry files; Bun loads `.env` files natively before code runs.
require('dotenv').config(); // ❌ Requires npm package + line-1 import orderingconst dbUrl = process.env.DATABASE_URL; // ✅ NEW: Automatically loadedInterview gotchas
Context
Interviewers test your knowledge of environment cascade overrides.
The mechanical answer
Bun loads `.env` files in the following priority order (higher overrides lower): 1. Existing system shell environment variables (highest) 2. `.env.local` (local developer overrides) 3. `.env.[NODE_ENV].local` (e.g. `.env.development.local`) 4. `.env.[NODE_ENV]` (e.g. `.env.production`) 5. `.env` (lowest / baseline defaults)
Trap
Variables already defined in the host operating system shell take absolute precedence and will not be overwritten by `.env` files.
Context
Checks CLI parameter knowledge.
The mechanical answer
Use the **`--env-file`** CLI flag: `bun --env-file=.env.custom run server.ts`. This instructs Bun to bypass default file discovery and load the specified file.
Trap
Passing `--env-file` multiple times allows chaining multiple custom configuration files.