Dotenv Environment Layered Loading

Layer environment configuration from shared defaults through environment-specific files up to process environment with explicit override rules.

JavascriptNodeConfig Management

Code

javascriptsnippet
29 lines
import { config } from 'dotenv';

const ENV = process.env.NODE_ENV ?? 'development';

// 优先级从低到高:共享默认 → 环境专属 → 容器注入的进程环境
config({ path: '.env.defaults', quiet: true });
config({ path: `.env.${ENV}`, quiet: true });

const layered = { ...process.env };

const required = ['DATABASE_URL', 'REDIS_URL'];
const missing = required.filter((key) => !layered[key]);
if (missing.length > 0) {
  console.error('missing required env vars:', missing.join(', '));
  process.exit(1);
}

export const settings = Object.freeze({
  env: ENV,
  databaseUrl: layered.DATABASE_URL,
  redisUrl: layered.REDIS_URL,
  featureFlags: (layered.FEATURE_FLAGS ?? '').split(',').filter(Boolean),
  http: {
    port: Number(layered.PORT ?? 3000),
    bodyLimitMb: Number(layered.BODY_LIMIT_MB ?? 1),
  },
});

console.log('config resolved for', settings.env, 'port', settings.http.port);

How the snippet works

Everything borrowed from dotenv is visible in one line: config.

The file’s state is a handful of top-level bindings: ENV, layered, required, missing.

Configuration comes from the environment — it reads NODE_ENV, so the same code switches behavior between environments without edits.

Emits through the .error level methods with structured payloads, so downstream transports can route by level and field.

What to watch for

  • Plan for an install step: dotenv is a real dependency, resolved by the package manager.

Applying it

The primary signature is export const settings =

The demo output is labeled (missing required env vars:, config resolved for), so every printed line maps back to its originating operation.

settings is the public entry point; everything else in the file exists to support it.

Statements that matter

const missing = required.filter((key) => !layered[key]);
const ENV = process.env.NODE_ENV ?? 'development';

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `dotenv`. Add it to your project before running the snippet.