Skip to main content

22 posts tagged with "Node.js"

View all tags

drizzle migration skipped silently? Check the journal first

Β· 7 min read

On a Node.js + PostgreSQL multi-tenant system, a deploy printed "no pending migrations", everything stayed green β€” and about 18 minutes later production hit "relation does not exist". The batch shipped a create-table migration that had never executed, and the application container logs held not a single error.

TL;DR​

drizzle decides "which migrations are applied" from two ledgers: drizzle.__drizzle_migrations in the database (execution ledger) and drizzle/meta/_journal.json (registration manifest). Either can break silently. Hand-edited future timestamps inflate the execution ledger's max(created_at) β€” the watermark migrate uses β€” pinning every later migration below it; a raw SQL file dropped into drizzle/ without journal registration never enters the pending list. Fix: register hand-written migrations via generate --custom, never hand-edit the ledgers, and put a "journal count = file count" gate in the deploy pipeline.

Symptoms: two incidents, two broken ledgers​

Incident one: migrate reports success, the next step fails on a missing table. pnpm db:migrate (drizzle-kit migrate) finished with normal output; the following step, applying RLS policies, failed with relation "task_assignees" does not exist β€” the create-table migration it depends on (0032) had not run, yet migrate's output and exit code showed nothing wrong.

Hand-fixing the ledger and re-running migrate produced a second problem: the tool re-applied 0028 and 0029, two migrations long since applied. __drizzle_migrations accumulated duplicate and orphan rows β€” 34 rows for 32 migration files.

Incident two: the deploy says "no pending migrations", production lacks the table. Another release carried a hand-written create-table SQL (0037). The deploy's migration check reported no pending work; nobody noticed, and the application container started normally. The missing table surfaced only when the WeCom-side department sync failed. Roughly 18 minutes ran with production missing the table and zero errors in the logs.

Post-incident reconciliation: journal 36 entries, production ledger 36 rows β€” both sides "consistent", each one entry short. The 0037 SQL file sat in drizzle/ with no journal registration.

Root cause: how drizzle decides "which migrations are applied"​

The decision reads only the ledgers, and each pit corrupts one of them.

The watermark: the ledger's max(created_at) is the only waterline. drizzle-orm's migrate uses the largest created_at in the ledger as the watermark and applies only journal entries whose when is greater. The setup for incident one came earlier: to force a re-apply, someone had hand-edited when values in _journal.json to future timestamps (like 1794716400000). After the journal was normalized back to real chronology, the future created_at rows were still in the ledger β€” the watermark stayed high, and 0032, whose when sat below it, could never satisfy "when > watermark". Skipped forever, no output.

Hashes are computed at execution time, so re-runs insert new rows. The hash migrate uses for bookkeeping is computed from the SQL file's content when it executes, not read from the ledger. That explains the second half of incident one: the old migrations re-running were not considered "already applied", and each inserted a fresh ledger row β€” hence the duplicates and orphans (34 > 32).

A raw file outside the journal is invisible to the pending list. The pending list is effectively the journal entries minus the ledger rows. 0037 had no journal entry: journal 36 = ledger 36, the difference was empty, so "no pending migrations". Tests did not catch it either: the catalog/integration tests run against a test database cloned from dev, and dev had already received 0037 by direct psql, with a bookkeeping row to match β€” structure complete, everything green. Of the three ledgers (journal, dev, test), exactly one was wrong and the other two agreed.

Fix: register through the proper channel, gate the deploy​

Hand-written migrations must go through generate --custom:

# Back up first! The command overwrites an existing file of the same name
cp drizzle/0037_departments.sql /tmp/0037_backup.sql
pnpm exec drizzle-kit generate --custom --name=departments
# Put the SQL into the generated stub; journal and snapshot register automatically

Never hand-edit journal when or ledger created_at β€” normalize what was edited: restore when to real chronology; delete duplicate/orphan ledger rows and align created_at with the journal; then verify three things β€” ledger rows = file count, max(created_at) matches the last migration, and a re-run of migrate is a no-op. Incident one cleared up in that order, and later migrations resumed applying.

Two hard rules for the deploy pipeline:

  1. Journal count β‰  drizzle/*.sql file count β†’ halt the deploy and print the mismatched filenames. This is the only reliable signal of an unregistered raw file β€” the database-side ledger can look "normal" because dev was hand-applied.
  2. The output says "no pending migrations" while the batch ships migration files β†’ contradiction. Stop and inspect the journal.

The ledger decision behind migrate, and where the two pits sit

The gate has caught a real case: after registering 0037, the journal held 37 entries, the deploy re-identified 1 pending migration, and the owner channel β€” per-file psql ON_ERROR_STOP, server-side sha256 bookkeeping, ownership and policy checks β€” completed with the ledger reconciled at 37/37. Why that owner channel replaced drizzle-kit migrate on the deploy path in the first place (a different pit: the ledger diverging from the actual tables) is in the companion post drizzle-kit migrate: exit 0 but no tables? Audit the journal β€” together the two posts map the whole ledger: that one covers ledger-vs-database, this one covers the ledger corrupting itself.

Watch out

  • drizzle-kit generate --custom overwrites an existing file of the same name β€” back up the hand-written SQL before generating, then fill the stub. Do not let the tool silently eat your file.
  • Run the count check twice over: journal vs file count (registration completeness), ledger vs journal (execution completeness). Incident two's 36 = 36 shows why one comparison is not enough.
  • When hand-inserting ledger rows, match the existing row shape (hash = sha256 of the full SQL file, created_at as a bigint epoch in seconds); mixed formats break later reconciliation β€” details in the companion post.

FAQ​

Why is drizzle-kit migrate not applying my migrations?​

Two ledgers, two failure modes. Count drizzle.__drizzle_migrations against the number of SQL files in drizzle/ β€” a mismatch means an unregistered file that will never apply. If the counts match, check drizzle/meta/_journal.json: any entry whose when is below the ledger's max(created_at) is pinned below the watermark and silently skipped forever.

Can I edit drizzle's journal manually?​

Leave the when fields in _journal.json and the created_at values in the ledger alone. migrate uses the ledger's max(created_at) as the watermark and only applies entries with when greater than it β€” a future timestamp inflates the watermark permanently, and later migrations stay skipped even after you normalize the journal.

How do I add a hand-written migration to drizzle properly?​

Never drop a SQL file straight into drizzle/ β€” without a journal entry it is invisible to the pending list and will never execute. Generate the file with drizzle-kit generate --custom --name=xxx (which registers the journal and snapshot) and put the SQL into the generated file.

CCLEE

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

Work with me

Map field arrives as {}? JSON.stringify skips Maps entirely

Β· 6 min read

Ran into this on an estimation endpoint of a Node.js + Fastify service: the response came back 200 with a healthy body, except one field β€” the per-row dates the client needed were missing because estimates was always {}, whatever parameters were sent.

TL;DR​

JSON.stringify(new Map([['a', 1]])) returns '{}'. A Map's entries live in an internal slot, not in own enumerable properties β€” and stringify only walks own enumerable properties. Fastify and Express both default to JSON.stringify and special-case nothing. Returning a Map from the core layer is fine; the bug is passing it through the route untouched. Fix: Object.fromEntries(map) before the response leaves.

Symptoms​

The client received {} for estimates on every call β€” status 200, a healthy response body, no server-side error, regardless of parameters. The endpoint follows the usual shape β€” the server computes a schedule, the client renders rows β€” and the route handed the core function's return value straight to the response:

app.post('/api/projects/:id/preview', async (req, reply) => {
const r = await recalcProject({ projectId: req.params.id, /* ... */ });
return { estimatedEnd: r.estimatedEnd, estimates: r.estimates };
});

What the client received:

{
"estimatedEnd": "2026-10-29",
"estimates": {}
}

estimatedEnd was fine; estimates was permanently empty. Server-side logs showed the field present, typed Map, with the right number of entries β€” the same value crossed the HTTP boundary and vanished. Because the status was 200 and nothing errored, the first instinct was a client-side field-access bug, and investigation spent a while on that side β€” until logging JSON.stringify(r.estimates) on the server, which printed {}.

One line reproduces it:

JSON.stringify(new Map([['a', 1]]));        // '{}'
JSON.stringify(new Set([1])); // '{}'
JSON.stringify({ m: new Map([['a', 1]]) }); // '{"m":{}}'
JSON.stringify(new Date('2026-01-05')); // '"2026-01-05T00:00:00.000Z"'

Three empty results, one that works.

Root cause: stringify only walks own enumerable properties​

JSON.stringify serializes objects by enumerating their own enumerable properties and turning each into a JSON key-value pair. A Map fails the premise entirely: its entries live in the internal [[MapData]] slot defined by the ECMAScript spec, reachable only through get/forEach and friends, never as properties. An instance has 0 own enumerable properties, so the output is {}.

Set is the same story ([[SetData]]). Date is the counter-example β€” it implements toJSON(), which stringify calls first, hence the ISO string.

No framework will save you here. Fastify's default JSON serialization is JSON.stringify (unless you register a fast-json-stringify schema), and so is Express's res.json. This is not a framework bug but a language-level behavior β€” and it decides where the failure lives: not in the compute layer, at the transport boundary.

In this codebase the core function returning a Map was reasonable: consumed internally, key-value semantics, convenient get. The mistake was the route passing the return value as-is into the HTTP response, with nothing along the chain checking "a Map is not a legal JSON value" β€” silent all the way through.

Fix: flatten at the transport boundary​

Convert the Map into a plain object explicitly, at the edge where the response leaves the server. The fix is one call:

return {
estimatedEnd: r.estimatedEnd,
estimates: Object.fromEntries(r.estimates), // Map<string, T> β†’ Record<string, T>
};

Object.fromEntries produces a plain object, and client-side estimates.a.plannedEnd resolves again.

More durable than the one-off fix is a boundary rule: before a route passes core return values into a response, check for non-POJO fields. The three common cases and their conversions:

Typestringify outputBoundary conversion
Map<K, V>{}Object.fromEntries(map)
Set<T>{}[...set]
DateISO string (fine)leave it; .toISOString() if you want uniformity

For a type-level cure, change the cross-boundary return type from Map<string, TaskEstimate> to Record<string, TaskEstimate> β€” TypeScript then forces every construction site to choose, and a missed conversion becomes a compile error instead of an empty field in production.

Watch out

  • An empty object errors nothing and alerts nothing; tests can stay green if they only assert on estimatedEnd and never on estimates entry counts. Give cross-boundary fields assertions at the "count > 0" level.
  • Maps nested deeper also become {} and hide better: in { rows: [{ est: new Map() }] } the casualty is rows[].est. When in doubt, JSON.stringify the suspect field β€” fastest way to see what the wire will carry.
  • Object.fromEntries flattens only the outermost layer; deeply nested Maps need recursive handling β€” or better, stop using Map at construction sites that feed serialized output.

Silent reshaping at serialization boundaries is not JS-only β€” the Python sibling bug is json.dumps with default=str turning a set into a string, where membership checks silently degrade into substring matching. Shared lesson: when the serializer meets a non-native type, convert explicitly β€” never let a fallback decide the shape for you.

FAQ​

Why does JSON.stringify(new Map()) return an empty object?​

JSON.stringify serializes an object's own enumerable properties, and a Map stores its entries in an internal slot instead of properties β€” zero own enumerable properties, so the output is {}. Nested Maps behave the same: JSON.stringify({m: new Map([['a',1]])}) gives {"m":{}}. Fix: Object.fromEntries(map) before serializing.

Why is my Map field empty in a TypeScript API response?​

TypeScript cannot catch it β€” a Map is a valid object and JSON.stringify throws no error; the failure is purely at the serialization boundary. Convert explicitly where the response leaves the server: estimates: Object.fromEntries(r.estimates), or type the cross-boundary field as Record<string, T> so plain objects are enforced at the source.

Do Set and Date serialize correctly with JSON.stringify?​

Set fails the same way: JSON.stringify(new Set([1])) is {} β€” spread it into an array with [...set]. Date works: it implements toJSON(), so JSON.stringify emits an ISO string like "2026-01-05T00:00:00.000Z". Rule of thumb: everything outside JSON's native types needs an explicit conversion at the boundary.

CCLEE

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

Work with me

drizzle-kit migrate: exit 0 but no tables? Audit the journal

Β· 9 min read

While shipping a batch of new tables for a multi-tenant system, drizzle-kit migrate on the deploy host printed "applying migrations" and exited quietly with code 0 β€” the application then started and its very first query failed on a missing table.

Ran into this in the deploy pipeline of a Node.js + PostgreSQL multi-tenant system (Drizzle ORM for migrations, row-level security isolating tenants, drizzle-orm 0.45.4 / drizzle-kit 0.31.11).

TL;DR​

Exit code 0 does not mean the migration applied. drizzle-kit's journal (the drizzle.__drizzle_migrations ledger) and the actual tables in the database are two different books: when the journal says "applied" but the table is missing, every later migration is skipped silently. Three steps: reconcile (journal count = migration file count, key tables present in information_schema) β†’ re-apply missing files with psql -v ON_ERROR_STOP=1 and insert the journal row by hand β†’ fix table ownership with OWNER TO. On the deploy path we retired drizzle-kit migrate entirely in favor of an owner pipeline: per-file apply + server-side journaling + verify-or-stop.

Symptoms: three errors, all exit code 0​

There are three layers to this, the first two in the migration command and the third right after it β€” none of them produce a failure signal on the command level. If you searched "drizzle migrate not working", "migrations applied but no tables", or "must be owner of table", read on.

Symptom one: the migration prints "applying", exits 0, tables missing.

$ drizzle-kit migrate
...
applying migrations...
$ echo $?
0

The local dev database hit the "journaled but not created" shape first β€” an interrupted migration left a half state behind, and every later migrate run treated that batch as applied and skipped it. Production hit the same problem in the opposite shape: migration 0019 exited 0 with neither the SQL applied nor the journal row written.

Symptom two: adding a foreign key fails with an unrelated error.

ERROR:  unrecognized configuration parameter "app.tenant_id"

Symptom three: with the key in place, the policy script stalls.

ERROR:  must be owner of table conflict_events

All three errors are segments of the same deploy pipeline.

Root cause: the journal and the schema are two different books​

The journal records "booked", not "the table exists". drizzle-kit migrate reads the SQL files in the migrations folder and decides what to skip by comparing hashes in drizzle.__drizzle_migrations β€” the journal is its only input. Once a "journaled row, missing table" intermediate state exists (most often left by an interrupted migration), every later migrate run believes that batch is done and skips it: no error, exit code 0. Production's 0019 was the inverse β€” neither applied nor journaled β€” but it surfaced the same way: caught by the ledger reconciliation, with no signal from the command itself.

Plainly put: this is a design where status is judged from the ledger alone, and when the ledger is polluted or never written, drizzle-kit offers no clue about it. Why it skips silently on the normal path, the command does not explain β€” our response was to stop trusting its judgment on the deploy path (the trade-off is explained in the fix).

Foreign keys meet RLS: the RI check runs without tenant context​

The referential-integrity trigger reading the referenced table does not carry your application's tenant injection. Multi-tenant tables usually have row-level security (RLS) policies that read a session variable via current_setting('app.tenant_id'). But the referential integrity (RI) check is an internal trigger scan: it runs on a bare connection that never SET app.tenant_id, so current_setting throws unrecognized configuration parameter β€” the foreign key isn't wrong, the policy blows up on that bare connection first.

The fix is one parameter:

current_setting('app.tenant_id', true)  -- returns NULL when unset

NULL matches no rows inside the policy (equivalent to deny), so the isolation semantics are unchanged while the RI check's bare connection stops erroring. For an RLS database the order becomes fixed: fix the policies first, then add the foreign keys.

Ownership drift: superuser-owned tables block policy application​

Policies can only be changed by the owner, and historical tables may be owned by someone else. The three tables apply-policies choked on (conflict_events, equipments, vendors) had been created manually by a superuser much earlier β€” owned by postgres, not by the owner role migrations run as. CREATE POLICY requires the table owner; with the wrong owner, applying all 15 policy files stalls.

Reclaim ownership:

ALTER TABLE conflict_events OWNER TO app_owner;

And audit the whole database β€” this query must return 0 rows:

SELECT tablename FROM pg_tables WHERE tableowner <> 'app_owner';

Fix: reconcile β†’ re-apply β†’ reclaim β†’ harden the deploy path​

For 0019 the order of events was: fix the policy, add the foreign key, get blocked again by table ownership β€” after reclaiming the three tables, all 15 policy files applied, and only then did the journal check reveal that 0019 had never been applied or recorded. Later, 0020 skipped silently on the same pipeline, and this time the deploy entry's ledger check stopped it before the half-applied state went live. After those two recurrences, the deploy-path migration became a fixed shape:

  1. Reconcile (a fixed step after every migration):
SELECT count(*) FROM drizzle.__drizzle_migrations;
-- must equal the number of files in the migrations folder

SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
-- key tables must actually exist
  1. Re-apply: for missing journal rows, pipe the SQL in as the owner role, then add the journal row:
psql -v ON_ERROR_STOP=1 -U app_owner -d appdb < drizzle/0019_missing.sql
# journal row: hash = sha256 of the full SQL file; created_at = epoch seconds (bigint), matching existing rows
  1. Reclaim: check owners, ALTER TABLE … OWNER TO app_owner (previous section), re-run policy application.

  2. Harden the deploy: replace "run drizzle-kit migrate once" with a per-file loop β€” apply each file with ON_ERROR_STOP and stop on the first failure, compute the journal hash server-side, and reconcile the count at the end:

for tag in $pending; do
psql -v ON_ERROR_STOP=1 -U app_owner -d appdb < "drizzle/$tag.sql"
hash=$(sha256sum "drizzle/$tag.sql" | cut -d' ' -f1)
psql -d appdb -c "INSERT INTO drizzle.__drizzle_migrations (hash, created_at)
VALUES ('$hash', extract(epoch from now())::bigint)"
done
# final check: journal count = local migration file count, otherwise abort the deploy

Deploy-time migration: the owner pipeline

The trade-off: why not keep drizzle-kit migrate? What a deploy needs is not "let the tool decide" but "the applied result is verifiable, and any failure stops the run". Per-file application turns every action into an assertable atomic step, and the ledger reconciliation turns "silently skipped" into an explicit failure. Local development keeps using the package.json db:migrate script (drizzle-kit migrate plus policy application) β€” what retired is the deploy usage, not the tool.

That owner pipeline guards against the journal and the schema diverging β€” but the ledger itself can be corrupted: hand-edited future timestamps in _journal.json inflate the watermark max(created_at) and pin every later migration below it, and a raw SQL file without journal registration never enters the pending list. Both shapes and their fixes are in the companion post drizzle migration skipped silently? Check the journal first.

The same family of "the migration looked done" exists on the SQLAlchemy side: three Alembic migration pitfalls (async engine misuse, broken revision chains, model changes without migrations). To systematize existence and ownership checks, see auditing orphan tables with information_schema.

Watch out

  • Run both checks after every migration: journal count = migration file count, and the key tables exist in information_schema. Both passing is what "migration complete" means; the exit code alone is not evidence.
  • Manual journal rows must match the existing format: hash is the sha256 of the full SQL file, created_at is epoch seconds as bigint β€” keep the same types drizzle-kit writes, or later reconciliations drift.
  • Run migrations as the owner role, always: tables created by a superuser are owned by the superuser, and the next policy application stalls for sure. The owner check belongs in the post-migration checklist.

FAQ​

Why does drizzle-kit migrate exit 0 without creating tables?​

The journal and the schema have diverged. Reconcile two counts: SELECT count(*) FROM drizzle.__drizzle_migrations; must equal the number of migration files, and information_schema.tables must contain the tables. Re-apply the missing SQL with psql -v ON_ERROR_STOP=1 and insert the journal row manually (hash = sha256 of the SQL file).

drizzle-kit migrate vs push β€” which one for production?​

migrate applies versioned SQL files tracked in a journal β€” one journal row per file; push diffs the schema directly with no history. Versioned files plus a verification step fit production better β€” but don't trust the exit code alone: reconcile the journal against the actual tables after every run.

How do I verify drizzle migrations were actually applied?​

Two counts plus one ownership check: the journal count equals the migration file count, the new tables exist in information_schema.tables, and SELECT tablename FROM pg_tables WHERE tableowner <> 'owner_role'; returns 0 rows β€” otherwise policy application fails with "must be owner of table".

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

process.env Not Propagating? It's the ESM Import Cache

Β· 5 min read

A login script successfully refreshed the credential at runtime and wrote it into process.env. Business requests still return 401 β€” the constant they imported is still the stale value from process startup.

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

TL;DR​

An ESM module evaluates exactly once; what you import is a read-only snapshot from load time β€” no later write to process.env ever reaches an already-imported constant.

// ❌ cached at load time, stale forever after
import { AUTH_TOKEN } from './config.js'

// βœ… read the current value on every use
function getToken() {
return process.env.AUTH_TOKEN || ''
}

One-sentence rule: a value that updates at runtime must be read dynamically from process.env at the call site β€” never imported as a module-level constant.

Symptoms​

Three files, three jobs: config.js exports config constants, login.js logs in and refreshes the credential, runtime.js sends business requests with it:

// config.js β€” central export
export const AUTH_TOKEN = process.env.AUTH_TOKEN || ''
// login.js β€” refresh after login
process.env.AUTH_TOKEN = newToken // runtime update
console.log('[login] token refreshed')
// runtime.js β€” business requests
import { AUTH_TOKEN } from './config.js'

fetch(url, { headers: { Authorization: `Bearer ${AUTH_TOKEN}` } })
// β†’ 401: AUTH_TOKEN is still the startup-time value (or an empty string)

Logs say the token was refreshed; the request header carries the old credential. Print AUTH_TOKEN and process.env.AUTH_TOKEN side by side and they differ β€” process.env is current, the imported constant is not.

Root Cause: An ESM Module Evaluates Only Once​

Per the ESM specification, a module's code executes exactly once β€” from its first import until the process exits; every subsequent import receives the same cached module instance.

So import { AUTH_TOKEN } from './config.js' in runtime.js actually means: load config.js (evaluating export const AUTH_TOKEN = process.env.AUTH_TOKEN || '', which freezes the then-current process.env value into the constant) and bind that value into runtime.js's scope.

Two properties of that binding create the trap:

  1. Read-only: the imported binding in the consumer cannot be reassigned (ESM import bindings do point at the export's live binding β€” but config.js exports a const, which will never hold a new value)
  2. Decoupled from process.env: process.env.AUTH_TOKEN = newToken executed later by login.js merely sets a property on the process.env object β€” the evaluation in config.js finished long ago, and no mechanism propagates that write back into the exported constant

In one sentence: process.env is a mutable runtime object, and export const X = process.env.Y is a one-time snapshot of one of its rows. The snapshot does not track the original.

The Fix: Read Dynamically at the Call Site​

Option 1 (smallest change): read the current value on use. Replace the imported constant with a process.env read:

// runtime.js
// import { AUTH_TOKEN } from './config.js' ← remove

fetch(url, {
headers: { Authorization: `Bearer ${process.env.AUTH_TOKEN || ''}` },
})

Option 2 (many call sites): centralize in a getter. When usage is scattered, consolidate into a function that evaluates on call:

// config.js β€” export a function, not a constant
export const getToken = () => process.env.AUTH_TOKEN || ''
// runtime.js β€” evaluated at call time, always current
import { getToken } from './config.js'

fetch(url, { headers: { Authorization: `Bearer ${getToken()}` } })

Option 3 (many config keys): export an object, read by property. Property access is dynamic by nature:

// config.js
const env = {
get token() { return process.env.AUTH_TOKEN || '' },
}
export default env

// runtime.js
import env from './config.js'
env.token // reads process.env on every access

All three share one principle: defer evaluation from module load to every use.

The same tool hits a second env-file trap after packaging (userData directory, not cwd) β€” a sibling problem about when and where config is read, covered in Packaged Electron App Can't Read .env? It Lives in userData.

Watch out

dotenv behaves identically: dotenv.config() reads the .env file exactly once, at call time. Editing the file afterwards, or calling plain config again, does not update already-injected values (override: true does overwrite, but only for code that reads process.env afterwards β€” anything imported as a constant stays dead). For "I changed .env but nothing happened": first check whether the process restarted, then whether the value was imported as a constant.

FAQ​

How should Node.js environment variables be configured and read?​

Configure via a .env file with dotenv or system-level exports; read them dynamically as process.env.XXX everywhere in code. The key takeaway: process.env is the only channel that runtime updates propagate through β€” a constant imported at module top level is fixed at first load and never follows later changes.

Why do other modules still see the old value after process.env is updated?​

Because the consuming module says import { TOKEN } from './config.js' β€” that line evaluates once at first module load, copying the value of that moment into a local constant. Nothing afterwards, inside config.js or on process.env, propagates back into it. Read process.env.TOKEN at the call site instead to always get the current value.

Do I need to restart the process after updating the .env file?​

Restarting is the reliable answer: dotenv.config() reads the file exactly once, at call time. For in-process hot reloads you must call dotenv.config({ override: true }) again AND have every consumer read process.env dynamically β€” a single import-as-constant anywhere breaks the propagation chain.

CCLEE

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

Work with me

npm audit Findings Attributed to the Wrong Directory? Match Package Trees by audited N

Β· 5 min read

While deploying a multi-package project (frontend and backend sharing one repository), npm audit reported 3 high vulnerabilities in the deploy log. We logged them against the backend β€” only to confirm later that all 3 highs lived in the frontend tree, and the backend had been a separate set of moderates all along.

Encountered this while building AI Analytics β€” an LLM-powered analytics platform that surfaces market trends, user behavior, and sales data; the frontend lives at the repository root and the backend in server/, deployed separately from one repo.

TL;DR​

npm audit summary lines carry only counts, no path. When a deploy pipeline runs npm install in several directories in sequence, the outputs interleave and the summaries become unattributable. The fix: use each package tree's unique fingerprint β€” the N in audited N packages β€” to attribute findings first, then pin the vulnerable transitive dependencies with overrides in package.json. A second deploy brought both sides to zero.

Symptoms​

The deploy script runs npm install in the frontend (repo root) and then the backend (server/), and both outputs land in the same log stream:

# Deploy log (summary lines carry no path)
added 546 packages in 41s
found 3 high severity vulnerabilities

added 372 packages in 24s
found 4 moderate severity vulnerabilities

Our handover notes attributed the "3 high" to server/. Chasing the backend dependency chain led nowhere β€” the server/ audit, run locally or on the server, consistently showed 4 moderates and never a single high. "Visible in the log, unattributable in practice" is a chronic disease of mixed deploy pipelines; our earlier write-up on stale build artifacts after deployment is the same family of problem.

Root Cause​

The npm audit summary only prints "found X vulnerabilities" with no directory info, and the adjacent audited 546 packages rarely registers as an attribution clue. Two package trees with wildly different sizes (546 vs 372) turn out to be the only stable fingerprint.

The frontend root installs the full Vite + React + Ant Design Pro stack, so its tree is large; @ant-design/pro-components β†’ @ant-design/pro-layout pulls in an old path-to-regexp, which is exactly where the 3 highs came from. The backend server/ is a lean Express + tsx tree whose only issue is the tsx β†’ @esbuild-kit/core-utils β†’ old esbuild chain of moderates.

Solution​

Step 1: Attribute findings by audited N​

Run npm install in each directory locally (or read added N packages straight from the deploy log) and record the tree sizes:

cd <repo-root> && npm install 2>&1 | tail -2   # added 546 packages ...
cd server && npm install 2>&1 | tail -2 # added 372 packages ...

In the deploy log, found 3 high immediately follows added 546 β†’ frontend; 4 moderate follows added 372 β†’ backend. Get attribution right before touching any dependency.

Step 2: Expand the vulnerability chain​

npm audit                # see the Path field, full chain
npm ls path-to-regexp # or reverse-lookup who depends on a package

The frontend output confirmed the chain: @ant-design/pro-components β†’ @ant-design/pro-layout β†’ path-to-regexp (old version, 3 high).

Step 3: Pin the transitive dependency with overrides​

Frontend root package.json:

{
"overrides": {
"path-to-regexp": "^8.4.2"
}
}

Backend server/package.json (with tsx bumped to a newer release):

{
"overrides": {
"@esbuild-kit/core-utils": {
"esbuild": "^0.25.12"
}
}
}

overrides supports nested syntax, scoping the pin to the child dependency under one specific parent β€” more surgical than overriding a package name globally.

Step 4: Reinstall and verify​

rm -rf node_modules package-lock.json && npm install && npm audit

After redeploying both sides, audit reports 0 vulnerabilities on each.

Notes

  • overrides requires npm 8.3+ and only takes effect in the package root package.json; run npm install afterward to refresh the lockfile, or nothing changes.
  • Pinning across a major version (e.g. old path-to-regexp β†’ 8.x) can break the APIs of packages that depend on it. Make sure the build passes and regression-test key pages before merging β€” don't stop at "audit says zero".
  • The "audited N" fingerprint is only reliable while the tree is stable: any dependency change shifts N. Fine for attribution during an incident, but don't hard-code it as an assertion in long-lived scripts.

FAQ​

Why is npm audit fix not working?​

npm audit fix only upgrades versions inside the allowed semver range. When the vulnerability lives in a transitive dependency whose version is pinned by an upstream package's range, fix cannot touch it. Use overrides in package.json to force the version, then reinstall.

How do I find which dependency chain an npm audit finding comes from?​

Read the Path field in the full npm audit output β€” it lists the complete chain from a direct dependency down to the vulnerable package. You can also reverse-lookup with npm ls <package>. Summary lines carry counts only.

How do I map npm audit results to a specific subproject?​

Deploy log summaries carry no directory name, so match them by each directory's added N packages / audited N packages tree size. Run npm install once per directory locally, record each N, and the mapping stays stable.

CCLEE

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

Work with me

systemctl Shows inactive But the Process Is Running? Bare-Process Health Check False Negative

Β· 5 min read

While building a server health-check endpoint, systemctl is-active redis-server returned inactive β€” yet Redis was happily serving requests.

Encountered this while building AI Analytics β€” LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operations strategy. The monitoring dashboard needs to reflect the real status of every infrastructure component, and Redis was reporting a false negative from the start.

TL;DR​

systemctl is-active only works for services that systemd manages through unit files. If Redis (or any service) runs as a bare process with no .service unit, systemctl can never see its true state and returns inactive (exit code 3). Reliable probing has to bypass systemctl and ask the process (pgrep) or the port (ss) directly.

Symptoms​

The probe called systemctl is-active for both Nginx and Redis:

$ systemctl is-active nginx
active # βœ… fine

$ systemctl is-active redis-server
inactive # ❌ looks like Redis is down
$ echo $?
3 # exit code 3 = inactive

But every business endpoint was reading and writing Redis fine β€” only /api/v1/server-monitor/status reported Redis as down.

Root Cause​

systemd is a process manager, and it only knows about units it started and owns. When you run systemctl start redis-server (or let systemd read redis-server.service), systemd records that unit's state and is-active can return active.

On this server, Redis was started as a bare process β€” a direct redis-server invocation, or launched via nohup / a custom script, never registered as a systemd service. So:

  • There is no redis-server.service in systemd's unit list at all;
  • systemctl is-active redis-server can't find the unit, treats it as inactive, and returns exit 3;
  • Nginx, by contrast, is a standard systemd service, so is-active correctly reports active.

In one line: is-active reflects systemd's view, not the system process view. "The process is running" and "systemd knows it's running" are two different things.

Solution​

Switch the probe to a "systemctl first β†’ process/port fallback" chain. If systemctl hits, use it; otherwise confirm the process is actually alive with pgrep or ss. Use execFileSync (no shell, args passed as an array) to avoid command injection:

import { execFileSync } from "node:child_process";

/** Run a single command safely (no shell); unify non-zero exit to null */
function sh(cmd: string, args: string[]): string | null {
try {
return execFileSync(cmd, args, {
stdio: ["ignore", "pipe", "ignore"],
timeout: 2000,
})
.toString()
.trim();
} catch {
return null; // inactive / process missing / timeout all land here
}
}

/**
* Probe whether a service is up: systemctl first, bare-process fallback.
* @param unit systemd unit name (e.g. "nginx")
* @param proc process name (e.g. "redis") for the pgrep fallback
* @param port listening port (e.g. 6379) for the ss fallback
*/
function isServiceUp(unit: string, proc?: string, port?: number): boolean {
// 1. Try systemctl first (standard systemd services)
const st = sh("systemctl", ["is-active", unit]);
if (st && st !== "inactive" && st !== "unknown") {
return true; // active, or activating/reloading etc.
}

// 2. Fallback A: find a PID by process name
if (proc && sh("pgrep", ["-f", proc])) return true;

// 3. Fallback B: confirm a listening port
if (port) {
const listening = sh("ss", ["-lnt"]);
if (listening && listening.includes(`:${port} `)) return true;
}

return false;
}

// Nginx: standard systemd service, systemctl hits directly
const nginxUp = isServiceUp("nginx");

// Redis: may be a bare process β€” pass process name + port as fallback
const redisUp = isServiceUp("redis-server", "redis", 6379);

The most robust final check at the application layer is to let the service answer for itself β€” Redis's PING, PostgreSQL's SELECT 1, an HTTP health endpoint. A listening port only proves "the process started", not "the service is ready", so on critical paths add one more application-level probe:

$ redis-cli ping
PONG # process alive + responsive = truly up

FAQ​

Why does systemctl is-active show inactive when the process is actually running?​

systemctl only queries services that systemd manages through unit files. If the process was started directly or with nohup as a bare process with no .service unit, systemd neither knows about it nor tracks it, so is-active can only return inactive (exit 3). That's a blind spot in systemd's view, not the process being down.

How do you reliably check whether a process is running?​

Don't rely on systemctl alone. Use pgrep <name> to find the PID, or ss -lntp | grep <port> to confirm a listening port β€” these inspect the system process table / network stack, independent of systemd management. For critical services, add an application-level probe (e.g. redis-cli ping) to verify both that the process exists and that it responds.

Caveats

  • Unit name β‰  process name: the redis-server in systemctl is-active redis-server is the unit name, which may differ from the actual process name (redis-server or redis). Don't conflate them.
  • Set a timeout in production: probe commands should have a short timeout (2s in the example above) and catch errors, so one stuck command doesn't drag down the whole monitoring endpoint.
  • Containerized services differ: services running in Docker aren't visible to the host's systemctl β€” use docker inspect or the container healthcheck API instead of the pgrep fallback here.
  • The real fix: migrate the bare process into a systemd unit (with Type=, Restart=always). Then is-active becomes accurate and you get systemd's auto-restart for free.

CCLEE

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

Work with me

JavaScript throw; is a SyntaxError? JS has no bare rethrow β€” you must throw e

Β· 5 min read

Wanting to "just pass the exception up unchanged" from a catch block, I reflexively wrote throw; β€” the bare rethrow I was used to in C# β€” and tsx/esbuild immediately failed to transform it: Unexpected ";".

Encountered this while building AI Analytics β€” an LLM-powered analytics pipeline that surfaces market trends, user behavior, and sales data for precise operations.

TL;DR​

JavaScript has no bare rethrow syntax. throw; (a bare throw) is a compile-time SyntaxError in all three toolchains: Node, tsc, and esbuild. To rethrow a caught exception you must throw e (the catch block needs a binding); to throw a new one, throw new Error(...).

The symptom​

The same throw; produces differently-worded errors across toolchains, but all of them are syntax errors (not runtime errors):

try {
something();
} catch {
throw; // ← bare rethrow
}
ToolchainError
tsx / esbuildERROR: Unexpected ";" (transform fails)
Node.js native (.js / .mjs)SyntaxError: Unexpected token ';'
TypeScript compiler (tsc)error TS1109: Expression expected.

The misleading one is esbuild's Unexpected ";" β€” it's tempting to read as "esbuild/tsx doesn't support some newer syntax." But run the same snippet through native Node and you get the identical SyntaxError. This isn't a tool limitation; the language itself has no such form.

Root cause​

The ECMAScript throw statement mandates an expression:

ThrowStatement : throw Expression ;

That is, throw must be followed by a value (throw err, throw new Error(), throw "fail") β€” the slot before the semicolon cannot be empty. JavaScript has no "bare throw = rethrow the current exception" semantics, which is the key difference from C# / Java / Python:

LanguageRethrow current exceptionNeeds caught variable
C#throw;no
Javathrow e;yes
Pythonraiseno
JavaScriptthrow e;yes

One common confusion: ES2019 added optional catch binding (catch {} may omit the parameter), but that is orthogonal to bare throw. Even with a binding present, throw; still errors β€”

try { f(); } catch (e) { throw; }   // still a SyntaxError; e is NOT auto-fed to throw

Confirmed in tsx as Unexpected ";". The expression after throw cannot be omitted; there are no exceptions.

The fix​

Pick the form that matches your intent:

// 1. Rethrow the original exception β€” the most common need
try {
doWork();
} catch (e) {
log(e);
throw e; // βœ… include e
}

// 2. Wrap in a new exception
try {
doWork();
} catch (e) {
throw new Error(`failed: ${e.message}`); // βœ… throw + expression
}

// 3. With ES2019 catch {} (no parameter), there is nothing to rethrow β€” throw new
try {
doWork();
} catch {
throw new Error("doWork failed"); // βœ… throw; here would be wrong
}

A minimal runnable repro and fix β€” run it directly with tsx:

function risky(): void {
throw new Error("origin");
}

function rethrowOptional(): void {
try {
risky();
} catch (e) { // ← must receive e
console.log("caught, rethrowing");
throw e; // ← not throw;
}
}

try {
rethrowOptional();
} catch (e) {
console.log("recovered:", (e as Error).message); // origin
}

On the call stack: throw e reuses the same error object, whose .stack was captured at new Error time; rethrow does not overwrite it. Only throw new Error(...) generates a fresh stack from the current throw site. So "does rethrow lose the stack?" β€” no, as long as you don't construct a new error.

Another common exception-handling pitfall is a catch block that swallows the error entirely, surfacing as a silent failure β€” see Python task marked failed but no error? try/except swallowed it. Worth watching across every language.

Caveats​

Caveats

  • Optional catch binding is not the culprit: catch {} (ES2019) is legal on its own; the only problem is throw;. Don't add a parameter to catch just to "fix throw" unless you actually use the variable.
  • Same rule in async/await: try { await f() } catch (e) { throw; } is a SyntaxError inside async functions too β€” the rule doesn't distinguish sync from async.
  • Stack preservation: throw e keeps the original stack; throw new Error(...) refreshes it. Use the former when debugging and you need the earliest throw site.
  • Aligning cross-language habits: coming from C#/Python to JS, porting throw; / raise directly will always bite you; flag this pattern in code review.

FAQ​

How do you rethrow a caught exception in JavaScript?​

Use throw e, and catch must take a binding: catch (e) { ...; throw e; }. JavaScript has no bare rethrow β€” a standalone throw; is a SyntaxError that Node, tsc, and esbuild all reject at compile time. It is not a limitation of any single tool.

Does rethrowing an exception in JavaScript preserve the original stack?​

Yes. throw e reuses the same error object, whose .stack was captured when the error was constructed with new Error; rethrow neither overwrites nor resets it. Only throw new Error(...) generates a fresh stack from the current throw site β€” so if you want the earliest origin during debugging, use throw e.

How do you correctly rethrow inside a JavaScript try/catch?​

catch must receive the error and throw it back: try { ... } catch (e) { log(e); throw e; }. With ES2019's catch {} (parameter omitted) there is no variable to throw, so you can only throw new Error(...). Either way, throw must be followed by an expression β€” throw; is always illegal.

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

Node.js AsyncLocalStorage Returns undefined in a Callback? EventEmitter Escapes Its Context

Β· 5 min read

The request-logging middleware reads AsyncLocalStorage's traceId inside the res.on('finish') callback, and getStore() returns undefined β€” every response log ends up missing its traceId.

Encountered this while building the ecommerce data collection tool for a client β€” the server uses ALS to carry each request's traceId through the entire handling chain, but response logs stubbornly refused to correlate. The culprit turned out to be "late callbacks" losing the context.

TL;DR​

EventEmitter callbacks like res.on('finish') run outside the async context they were registered in, so als.getStore() can't find the request's store. The most reliable fix is to capture the value into a closure variable during the synchronous segment and use that closure inside the callback; when you need the full store, rebuild the context with als.run(store, fn) inside the callback.

The Problem​

An innocent-looking request-logging middleware:

// middleware/requestLog.js
import { als } from '../utils/als.js';

app.use((req, res, next) => {
res.on('finish', () => {
const store = als.getStore();
logger.info({
traceId: store?.traceId, // always undefined in the response log
statusCode: res.statusCode,
}, 'request');
});
next();
});

The middleware order is fine, the traceId is readable everywhere else in the request chain (routes, business logic), but not inside res.on('finish'). The really confusing part: move als.getStore() into the synchronous segment before next(), and it has a value.

Root Cause​

AsyncLocalStorage relies on Node's async_hooks to bind the store to the currently active async context and propagate it down the async call chain. The semantics of als.run(store, fn) are: during fn's execution (and any async tasks it spawns), getStore() returns this store.

The problem is EventEmitter. res.on('finish', cb) registers cb as a listener, to be fired by EventEmitter's dispatch loop after the response is sent. The async context that fires cb is the one active where dispatch happens β€” not the request's context. And since the response is usually sent after the request-handling chain, the als.run scope for that request may already have exited.

So als.getStore() inside cb reads the store of "whatever context is active right now," which doesn't belong to this request β€” the result is undefined (or worse, a different request's store).

Any callback with "registered in one context, fired in another" has this trap: res.on('finish'), once, some setTimeout/setInterval, chrome.alarms listeners, and so on.

Solution​

Two patterns, depending on what you need.

If your callback only needs a couple of values from the store (most often just traceId), the simplest and most robust approach is to capture them during the synchronous segment β€” when the store is guaranteed alive β€” into a closure, and use that closure in the callback without ever touching ALS:

app.use((req, res, next) => {
// Synchronous segment: we're inside the als.run scope, getStore() always has a value
const traceId = als.getStore()?.traceId;
const start = Date.now();

res.on('finish', () => {
// Use the closure's traceId, never touch ALS
logger.info({
traceId, // reliably present
statusCode: res.statusCode,
durationMs: Date.now() - start,
}, 'request');
});

next();
});

This swaps the uncertainty of "is the async context still alive" for a deterministic closure reference. When the callback fires no longer matters β€” the value is already captured.

Pattern B: rebuild the context with als.run​

When the callback invokes a blob of code that internally depends on getStore() (a logger mixin, Sentry scope injection), rewriting each call to use a closure is impractical. Instead, rebuild the context at the callback's entry:

res.on('finish', () => {
const traceId = capturedTraceId; // value captured in the synchronous segment
if (traceId) {
// Re-establish the ALS context inside the callback so record()'s internal getStore() works
als.run({ traceId }, () => record(res, start));
} else {
record(res, start);
}
});

als.run(store, fn) creates a new, independent async context, binds the store to it, and makes it visible to fn and every async task it spawns. It's safer than als.enterWith β€” which mutates the "current shared context" and causes cross-talk under concurrency. That's a separate trap, covered in AsyncLocalStorage reads the wrong value under concurrency? Replace enterWith with run.

Caveats

  • To tell whether a callback will lose context, ask whether registration and firing are separated. res.on('finish'), once, and cross-tick setTimeout are suspect; await and fetch().then() inherit naturally along the async chain and need no handling.
  • Prefer pattern A. It reduces the problem to an ordinary closure β€” best readability, no implicit "context rebuild" behavior. Only reach for pattern B when the callback wraps a lot of existing code that depends on getStore().
  • Don't patch this with als.enterWith in the callback β€” it mutates the shared parent context under concurrency and causes cross-talk, a far harder bug to diagnose than a lost context.

FAQ​

Why can't I read AsyncLocalStorage inside the res.on('finish') callback?​

res.on('finish', cb) registers cb as an EventEmitter listener that only fires after the response is sent. The async context active when it fires is the dispatch context, not the request's, and the request's als.run scope may have already exited β€” so getStore() returns undefined.

How do I make an EventEmitter callback see the AsyncLocalStorage context again?​

The simplest way is to capture the value into a closure variable during the synchronous segment and use the closure in the callback. If the callback wraps a lot of code that depends on getStore(), rebuild the context at the callback's entry with als.run(store, fn). Prefer the former; reserve the latter for retrofitting existing logic.

CCLEE

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

Work with me