Skip to main content

6 posts tagged with "dotenv"

View all tags

.env Edits Do Nothing? DB Config Overrides Env Variables

Β· 6 min read

An AI model config in .env was changed β€” provider, key, and model name all swapped. Service restarted. The application's behavior did not move by an inch: still the old provider, the old model. The new config sits right there in the file, looking ready to apply at any moment. It never does.

Encountered this while maintaining a client-delivered AI content-processing application β€” recording the detour and the final diagnosis.

TL;DR​

When an app supports editing config through an admin UI, the database fully overrides .env β€” same-named entries in .env are a fallback at best, dead config at worst.

One sentence for the triage order: check the app's runtime config store (the DB config table) before checking .env. This investigation wasted two steps on .env and the process environment snapshot before the DB config table revealed the truth: it held a complete set of values from a different provider, shadowing .env in full.

Symptoms​

The server's .env:

# /path/to/backend/.env β€” looks "in use"
AI_API_KEY=sk-xxxx...xxxx
AI_BASE_URL=https://old-provider-compatible-endpoint
AI_MODEL=old-model-name

Actual behavior: model calls go to a different provider entirely (a real OpenAI-protocol endpoint, different key, different model). Edit .env, restart, no effect. Edit again, restart again, still no effect.

The Detour: Two Checks That Paid Nothing​

The investigation itself is worth recording β€” two checks that looked professional and accomplished nothing.

Detour 1: staring at the .env file. The config was complete, well-formatted, in the right directory (the systemd unit genuinely points there). Everything about it says "in use". But a config being in a file and a config being in effect are different things β€” the app's loader has a precedence chain, and .env is only one candidate source.

Detour 2: checking /proc/<pid>/environ. The standard move to see what environment a process actually received:

cat /proc/<pid>/environ | tr '\0' '\n' | grep AI_

Empty. And the check itself was flawed: dotenv injects into os.environ at runtime, after the process started β€” /proc/<pid>/environ is a snapshot from launch time and can never show dotenv-injected values. Absence here proves nothing about the process, and presence here proves nothing about effectiveness. For a dotenv app, this snapshot supports no conclusion in either direction.

The third step finally landed: querying the DB config table. The app supports editing AI config through an admin UI, and its loader is "DB first, env as fallback" β€” the DB config table held a full set of the other provider's values, outranking .env. Case closed.

Root Cause: A Config UI Requires DB > env​

Why must this class of app rank DB above env? Reverse-engineer from the feature requirement:

The app promises "admin edits AI config in the backend; it applies on save". If .env outranked the DB, every UI edit would be crushed by .env and the feature would be dead on arrival. So any app with this feature has a loader shaped like:

def _ensure_client():
cfg = load_db_config() # 1. DB config table first
if cfg is None: # 2. fall back to env only when DB is empty
cfg = from_env()
return build_client(cfg)

DB wins whenever it has values β€” and the moment anyone saves a config in the backend once, the DB has values forever. From that day on, .env is dead config: nothing written there gets read, unless the DB config is cleared.

The trap is its invisibility: .env sits right there on the server, complete and tidy, and the natural operator reflex is "edit this". Nothing ever warns "your edit was overridden by the DB" β€” the config system silently follows its precedence chain, and only someone who knows the chain can predict the outcome.

The Fix: Check the DB First, Then Clean Up​

Step 1: confirm the real source of effective config. Query the app's config table (an app_config-style key-value table in this case):

SELECT key, value FROM app_config;

Match the DB values against observed behavior (e.g., which endpoint requests actually hit). Once they line up, the conclusion is nailed: DB fully overrides; the same-named .env block is leftover dead config.

Step 2: before deleting dead config, verify the DB really covers everything. Compare DB entries against .env item by item: if DB covers all critical fields, removing the .env leftovers should be harmless in theory β€” but restart and verify before deleting, in case some field in the loader still falls back to env. Verify, then delete: that is the safe order for dead-config cleanup.

Step 3: write the precedence chain into the ops doc. The two wasted steps trace back to one gap: nobody knew this app had config precedence at all. One line in the handover doc saves the next person two hours: "config lives in the admin UI (DB); .env is fallback only β€” check the DB before touching .env."

Watch out

"A config file exists and looks correct" never equals "this config is in effect" β€” effectiveness depends on the loading logic and its precedence chain. Likewise, /proc/<pid>/environ proves neither presence nor effectiveness for a dotenv app. The right starting point for any config investigation is the app's config-loading code β€” read the precedence chain out of the code, then walk it.

FAQ​

What is the config precedence between database and environment variables?​

In apps with an admin config UI, from lowest to highest: system-level env vars β†’ process startup env β†’ dotenv-injected values β†’ the app's runtime config store (a DB or config file). The DB layer wins β€” UI edits must take effect immediately, which is impossible if .env outranks it. When troubleshooting, check the app's config store before the env files and you skip most of the detour.

Do environment variable changes require a restart?​

By layer: system-level variables need a shell or service restart; dotenv reads .env once at process start, so file edits need a process restart too; apps with a DB config layer pick up backend edits instantly β€” the loader reads the DB on every client build. Mixing the three timing models is how you end up concluding "changes do nothing".

Why can't I see dotenv variables in /proc/pid/environ?​

Because /proc/pid/environ is a snapshot from the instant the process started, while dotenv injects into os.environ after the process is already running. To verify dotenv's values, print them inside the process or read the .env file directly β€” and remember that a value being in the file still doesn't mean it's in effect; a higher-precedence layer may be overriding it.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Packaged Electron App Can't Read .env? It Lives in userData

Β· 5 min read

Configuration loads fine in development. After packaging the Electron app with electron-builder and installing it, every process.env.XXX is undefined and the modules that depend on them fail one after another.

Encountered this while building a data-collection tool for a client β€” recording the root cause and the fix.

TL;DR​

After packaging, .env is not in process.cwd() β€” it belongs in app.getPath('userData').

Three steps:

  1. On startup, the main process checks whether userData/.env exists; if not, it copies the bundled .env.example over (seeding)
  2. Store the full path in process.env.ENV_PATH
  3. The config module reads it with dotenv.config({ path: process.env.ENV_PATH || '.env' })

Symptoms​

In development (electron .) everything works. After installing the packaged build (launched from the dock or the start menu), the configuration is empty:

undefined
undefined
TypeError: Cannot read properties of undefined (reading 'xxx')

Extra confusing part: launching the same packaged binary from a terminal inside its own directory sometimes works β€” because process.cwd() happens to be the app directory in that case. Same build, different launch method, different behavior.

Root Cause: process.cwd() Is Unreliable After Packaging​

dotenv.config() without arguments reads process.cwd()/.env. But process.cwd() is "the directory the process was started from", not "the directory the app is installed in" β€” they only coincide during development:

Launch methodprocess.cwd()
Dev: electron . from the project rootproject root βœ“ .env is here
Windows: double-click the exethe exe's directory
macOS: double-click the .app/ (filesystem root)

After packaging, there are exactly two places .env could live, and both fail:

  • asar archives are read-only: electron-builder packs app resources into app.asar, mounted read-only at runtime. Even if you bundle .env inside, users cannot edit it β€” every config change would require a rebuild
  • The install directory is not writable: Program Files and /Applications require elevated permissions to write; a normally-launched app cannot write there

Electron provides a standard directory for "runtime data belonging to this user": app.getPath('userData'). It resolves per platform (macOS ~/Library/Application Support/<app>, Windows %APPDATA%\<app>, Linux ~/.config/<app>), and it is guaranteed to exist, be writable, and survive reinstalls. That is where .env should live.

The Fix: Seed + ENV_PATH​

The change touches two files, about a dozen lines total.

Step 1: seed on startup (electron/main.js, before any window or the Express server starts):

const fs = require('fs');
const path = require('path');
const { app } = require('electron');

// ── .env path setup ──
const userDataPath = app.getPath('userData');
const envPath = path.join(userDataPath, '.env');
// rootDir = the packaged app root; use app.getAppPath() or your project's convention
const envExamplePath = path.join(rootDir, '.env.example');

if (!fs.existsSync(envPath) && fs.existsSync(envExamplePath)) {
fs.copyFileSync(envExamplePath, envPath);
console.log(`[electron] .env copied to ${envPath}`);
}
process.env.ENV_PATH = envPath;

Logic: if userData has no .env, copy the bundled .env.example (read-only inside asar is fine β€” it is a template), then expose the final path as process.env.ENV_PATH.

Step 2: the config module follows the pointer (src/config.js):

import dotenv from 'dotenv';
dotenv.config({ path: process.env.ENV_PATH || '.env' });

The || fallback keeps non-Electron contexts working (running the same code under plain Node), so development behavior is unchanged.

Step 3: config changes without reinstalling. To change an environment, edit the .env inside the userData directory and fully quit and relaunch the app β€” dotenv reads the file once, at process start; edits do not apply to a running process.

This "userData holds runtime state" pattern carries more than env files: login sessions, caches, and logs all belong there. The same tool stores its cookie-based login state this way β€” that investigation is covered in Puppeteer Blocked by Anti-Bot? From Chrome CDP to an Electron Alternative.

Watch out

process.env.ENV_PATH must be set before the config module is imported β€” dotenv.config() reads the file at call time, not later. Do the seeding at the very top of the main-process entry file, not inside an app.whenReady() callback: if any module earlier in the import chain calls require('dotenv').config(), the path will not be there yet.

FAQ​

How do I use app.getPath('userdata') for config files?​

Call it in the main process before any window or server starts: app.getPath('userData') returns the per-user data directory β€” ~/Library/Application Support/<app> on macOS, %APPDATA%\<app> on Windows, ~/.config/<app> on Linux. Build your .env path with path.join(userDataPath, '.env') and it will be writable in every packaged build.

Why can't my packaged Electron app read .env?​

Because dotenv defaults to process.cwd(), which is the launcher's directory after installation β€” on macOS a double-click even sets it to / β€” while your app resources sit inside a read-only asar archive. The fix: seed .env into userData on startup and hand that exact path to dotenv.config({ path }).

Should .env.example be bundled into the app?​

Yes. Ship it as the first-run template inside the asar (read-only is fine for a template). On startup, if userData/.env does not exist, copy the example over. Users can then edit the copy directly to change configuration without reinstalling anything.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

dotenv truncates .env values at #? Quote and force-refresh

Β· 6 min read

Encountered this while building AI Ops β€” LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy.

TL;DR​

dotenv treats any # in unquoted values as an inline comment. KEY=value#hash is actually loaded as value, with #hash dropped β€” no warning, no error. The fix has two steps: wrap any .env value containing # in double quotes, then run pm2 restart <app> --update-env to force-refresh the process environment β€” without the refresh the edit changes nothing, because PM2 re-injects its cached snapshot into the new process.

Symptom​

Backend calls to an upstream service keep returning 401 Invalid credentials:

POST /api/v1/dag/trigger β†’ 500
Stack: Airflow JWT auth failed (401): {"detail":"Invalid credentials"}
at getJwtToken (airflow-client.ts)

My first assumption was a wrong password or a disabled account. Investigation shows the password written in .env is 24 chars and contains # and &:

AIRFLOW_PASSWORD=Aq7#mZx&V3nKp9RtWu2yBc4d

But the value loaded into process.env.AIRFLOW_PASSWORD is only 3 chars long β€” the 21 characters after # are gone. Calling the upstream auth endpoint with the full password via curl returns 201; calling it with the truncated value parsed from .env returns 401. The credential is fine; the value loaded from .env is truncated. If you searched for ".env not loading", "environment variable value wrong" or "password is correct but auth fails", it's all the same root cause.

Root cause: dotenv treats any # in unquoted values as an inline comment​

When dotenv parses a .env file, an unquoted value ends at the first # β€” everything from # onward is discarded as an inline comment, with no warning at all. This behavior is documented, but the silence is what makes it nasty β€” no error, no warning; newer versions print a one-line injected-env summary at startup (verified on 18.0.4), but it only shows how many keys were loaded.

I ran the same parse matrix against dotenv 16.6.1 (the version pinned in the project) and 18.0.4 (current latest at the time); the results were identical:

.env syntaxLoaded value
A=val#hashval
B=val #hashval
C="val#hash"val#hash
H='val#hash'val#hash
D=val&moreval&more
E=val with spaceval with space
I="val" # commentval

Three things stand out:

  • No space needed. In a shell, # only starts a comment when preceded by whitespace. dotenv doesn't care β€” val#hash with the # glued to the value is truncated all the same. Strong-random strings like JWT_SECRET, API_KEY, and DATABASE_URL frequently contain # in arbitrary positions β€” high-risk territory.
  • Quotes are the literal switch. Inside single or double quotes, # is kept as a plain character; a # after the closing quote still starts a comment.
  • & and spaces are safe in dotenv. Neither triggers truncation in the tests, and core dotenv does not expand $VAR (that's the dotenv-expand plugin's job).

The fix: quote the value, force-refresh the process environment​

First, wrap any value containing # in double quotes:

# truncated: the process actually gets Aq7
AIRFLOW_PASSWORD=Aq7#mZx&V3nKp9RtWu2yBc4d

# correct: preserved verbatim
AIRFLOW_PASSWORD="Aq7#mZx&V3nKp9RtWu2yBc4d"

Second, restart with --update-env:

pm2 restart analytics-api --update-env

That flag is not optional, because two "don't overwrite" defaults stack up:

  1. PM2 snapshots the environment when a process is first started and injects that stale snapshot back into every restart;
  2. dotenv does not overwrite keys that already exist in process.env (verified: set process.env.X='oldvalue', run dotenv.config(), and X is still oldvalue).

Editing the file without refreshing the process environment changes nothing β€” the process keeps reading PM2's cached snapshot. The same applies to docker compose and systemd: the service must actually rebuild its environment (docker compose up -d --force-recreate, systemctl restart).

After restarting, verify what the process actually loaded instead of guessing:

# print the length and compare it against the value in .env
node -e "console.log(process.env.AIRFLOW_PASSWORD.length)"

To go one step further, validate critical variable lengths at startup so a silent failure becomes a startup failure:

// Validate critical env vars at startup to catch truncation early
const required = ['AIRFLOW_PASSWORD', 'JWT_SECRET', 'DATABASE_URL'] as const;
for (const key of required) {
const v = process.env[key];
if (!v || v.length < 16) {
throw new Error(`${key} not loaded correctly (length ${v?.length ?? 0}); check .env quoting`);
}
}

Boundary cases: docker compose plays by different rules​

Truncation at # is not a universal env-parser convention β€” docker compose follows the opposite rule, and the same file can load differently across tools. The compose-spec states plainly: "Inline comments for unquoted values must be preceded with a space", and its official example shows VAR=VAL# not a comment loading as VAL# not a comment, kept verbatim.

Same line API_PASSWORD=Kx9#mPwdotenv (tested)docker compose (spec)
Loaded valueKx9Kx9#mPw

For dotenv alone, only # is dangerous; but one .env file often serves several tools β€” local shell, docker compose, PM2, CI β€” each with its own parser. Rather than memorizing every parser's quirks, our team settled on one hard rule: any value containing #, & or spaces gets double quotes. Two extra characters buy cross-tool predictability.

Watch out

  • Double quotes + no ${...}: for passwords you usually want the literal value β€” write it plainly inside double quotes.
  • Don't generalize dotenv's rules: compose requires a space before inline comments (see table above). When one file serves multiple tools, rely on quotes only.
  • Container injection is not affected: variables injected via environment: in Docker/Kubernetes don't go through dotenv; CI secrets (GitHub Actions, GitLab CI) injected into the env context bypass dotenv too. Only the .env file + dotenv.config() path is affected.

FAQ​

Why does a password with # in .env get shorter?​

dotenv treats any # in unquoted values as an inline comment and drops everything after it β€” KEY=value#hash loads as value, with no warning (verified on dotenv 16.6.1 and 18.0.4). Wrap the whole value in double quotes to preserve it.

How do I debug dotenv not working?​

Three steps: first confirm dotenv.config() runs before all imports (ES Module imports are hoisted statically β€” see debugging silent JWT signature failures); then check .env values for unquoted #; finally print process.env.XXX and diff its length against the .env source file β€” a mismatch means truncation, not a missing load.

Does docker compose treat # the same way in env files?​

No β€” the rules differ. compose-spec requires inline comments in unquoted values to be preceded by a space, so VAL=B#C is kept as-is; dotenv truncates it to B regardless of position. Double quotes are the only form consistent across tools.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

JWT Signing Silently Fails? Check Your Node.js Environment Variable Loading Order

Β· 3 min read

Encountered this issue while building a SaaS authentication system for a client. Here's the root cause and solution.

TL;DR​

In Node.js ES Modules, import statements execute before dotenv.config(). If module-level code reads process.env.JWT_SECRET, it gets undefined, causing JWT signing to use the string "undefined" as the secret β€” no errors thrown, but all token verification fails. The fix: lazy initialization.

The Problem​

JWT login returns 200, but all subsequent requests return 401. Investigation reveals:

  1. Tokens generated at login can't be verified by jwtVerify()
  2. Every server restart invalidates all previously issued tokens
  3. console.log(process.env.JWT_SECRET) outputs undefined
// jwt.ts β€” module-level code
import crypto from 'crypto';

// ❌ This line executes BEFORE dotenv.config(), JWT_SECRET is undefined
const SECRET = crypto.createSecretKey(
new TextEncoder().encode(process.env.JWT_SECRET)
);

The worst part: no error is thrown. new TextEncoder().encode(undefined) encodes the string "undefined" into bytes, producing a valid but wrong secret key.

Root Cause​

ES Module import statements are statically hoisted:

// server.ts (entry file)
import { router } from './routes/auth'; // ← runs first
import { authenticateToken } from './middleware/auth'; // ← runs first

dotenv.config(); // ← runs AFTER all imported modules execute

Execution order:

  1. Node.js scans all import statements and builds the dependency graph
  2. Executes all imported modules' top-level code depth-first (jwt.ts's const SECRET = ... runs here)
  3. Returns to server.ts, runs dotenv.config()
  4. Now .env is loaded into process.env

So jwt.ts module-level code reads process.env.JWT_SECRET as undefined.

Solution​

Move secret initialization into a function β€” env var is read on first call, not at import time:

import crypto from 'crypto';

let _secret: crypto.KeyObject | null = null;

function getSecret(): crypto.KeyObject {
if (!_secret) {
const secretValue = process.env.JWT_SECRET;
if (!secretValue) {
throw new Error('JWT_SECRET environment variable not set');
}
_secret = crypto.createSecretKey(
new TextEncoder().encode(secretValue)
);
}
return _secret;
}

// Use getSecret() everywhere the key is needed
export async function generateToken(payload: any): Promise<string> {
return new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.sign(getSecret()); // ← deferred until runtime
}

No dependency on entry file import order β€” safe regardless of when called.

Option 2: Call dotenv at the Very Top of Entry File​

// server.ts β€” ensure these lines come before ALL imports
import 'dotenv/config'; // or require('dotenv').config()
import express from 'express';
// ...other imports

Limitation: If another entry point (cron job, worker) forgets this line, the bug resurfaces.

Caveats​

Caveats

  • This pitfall affects all module-level env var reads, not just JWT β€” database connections, API keys, etc.; ESM module resolution has another common gotcha β€” missing .js extensions in dynamic imports causes module-not-found errors in production
  • require('dotenv').config() only guarantees order in CommonJS; ES Module import always executes before runtime code
  • Lazy initialization works well for: secrets, DB connection pools, external API clients, and other one-time resources; if you're using the jose library with Node 24, also watch out for KeyObject format changes