Configuration files

suggest change

Most programs need settings that change between machines or deployments: the port to listen on, a database address, a log level, API keys, feature flags. Hard-coding them means editing code to deploy, so they go in configuration instead.

Node.js programs usually take configuration from a mix of these sources:

Source Good for Built-in support
JSON file structured defaults committed to the repository JSON.parse, import ... with { type: 'json' }
.env file local development values for environment variables --env-file, process.loadEnvFile(), util.parseEnv()
environment variables per-deployment values and secrets (containers, CI, PaaS) process.env
command-line flags one-off overrides util.parseArgs()
YAML, TOML, INI hand-edited files with comments npm packages yaml, smol-toml, ini
JavaScript file config that needs logic or functions (eslint.config.js style) dynamic import()

This article shows how to read each of them, how to combine them into one config object, and how to validate the result. For the basics of process.env see Accessing environment variables, and for JSON in general see JSON.

The examples were run with Node.js 24, yaml 2.9, smol-toml 1.9, ini 7.0 and zod 4.6. The project's package.json has "type": "module".

JSON configuration files

JSON needs no packages and is the most common format. Here is config/default.json, used in several examples below:

{
  "port": 8000,
  "logLevel": "info",
  "db": {
    "host": "localhost",
    "port": 5432,
    "name": "shop"
  },
  "features": ["search"]
}

Reading it is readFile plus JSON.parse. The default errors don't say which file was the problem, so it's worth wrapping them:

import { readFile } from 'node:fs/promises';

async function loadJson(path) {
  let text;
  try {
    text = await readFile(path, 'utf8');
  } catch (err) {
    if (err.code === 'ENOENT') throw new Error(`config file not found: ${path}`);
    throw err;
  }
  try {
    return JSON.parse(text);
  } catch (err) {
    throw new Error(`invalid JSON in ${path}: ${err.message}`);
  }
}

const config = await loadJson('config/default.json');
console.log(config.port, config.db.host);

try {
  await loadJson('config/missing.json');
} catch (err) {
  console.log(err.message);
}
8000 localhost
config file not found: config/missing.json

JSON doesn't allow comments or trailing commas, and people editing config files by hand add them all the time. Node's error message includes the line and column, which helps:

// config/bad.json contains: { "port": 8000, }
JSON.parse(await readFile('config/bad.json', 'utf8'));
Expected double-quoted property name in JSON at position 18 (line 3 column 1)

Importing JSON as a module

If the file is part of your source tree and doesn't change while the program runs, you can import it:

import config from './config/default.json' with { type: 'json' };

console.log(config.db);
{ host: 'localhost', port: 5432, name: 'shop' }

In CommonJS the equivalent is const config = require('./config/default.json').

Imported JSON is loaded once and cached, the path is relative to the importing file (not the current directory), and a missing file is a startup error you can't catch with try. For files that users edit or that may be missing, use readFile.

.env files

A .env file holds NAME=value lines that are loaded into process.env. It's the usual way to give a program its environment variables during local development, without exporting them in every shell:

# local development settings
PORT=8100
DATABASE_URL=postgres://dev:secret@localhost:5432/shop
LOG_LEVEL=debug
GREETING="hello world"
MULTI="line one
line two"

Node.js reads .env files itself; the dotenv package is no longer needed.

--env-file

Pass the file on the command line:

// ex3.js
console.log(process.env.PORT, process.env.LOG_LEVEL);
console.log(process.env.GREETING);
console.log(JSON.stringify(process.env.MULTI));
$ node --env-file=.env ex3.js
8100 debug
hello world
"line one\nline two"

Variables that are already set in the environment win over the file. That's what you want: a deployment can override anything without editing the file.

$ PORT=9999 node --env-file=.env ex3.js
9999 debug
hello world
"line one\nline two"

A missing file passed with --env-file is a fatal error. Use --env-file-if-exists for optional files. You can pass several files; later files override earlier ones:

$ node --env-file=nope.env ex3.js
node: nope.env: not found

$ echo "LOG_LEVEL=trace" > .env.local
$ node --env-file=.env --env-file-if-exists=.env.local ex3.js
8100 trace
hello world
"line one\nline two"

In package.json scripts:

{
  "scripts": {
    "dev": "node --env-file-if-exists=.env --watch src/server.js",
    "start": "node src/server.js"
  }
}

process.loadEnvFile()

To load the file from code, call process.loadEnvFile(path). Without an argument it loads ./.env. It throws an ENOENT error if the file doesn't exist, and like --env-file it doesn't overwrite variables that are already set:

import { existsSync } from 'node:fs';

if (existsSync('.env')) {
  process.loadEnvFile('.env');
}
console.log(process.env.DATABASE_URL);
console.log(typeof process.env.PORT, process.env.PORT);
postgres://dev:secret@localhost:5432/shop
string 8100

Load the file before importing modules that read process.env at the top level. Static import statements run before the code in your file, so either load the file in a separate module imported first, or use --env-file.

util.parseEnv()

util.parseEnv() parses .env content into a plain object without touching process.env. It's handy when the values are for something else, like a child process or a test:

import { parseEnv } from 'node:util';
import { readFile } from 'node:fs/promises';

const vars = parseEnv(await readFile('.env', 'utf8'));
console.log(vars);
console.log(process.env.LOG_LEVEL);
{
  DATABASE_URL: 'postgres://dev:secret@localhost:5432/shop',
  GREETING: 'hello world',
  LOG_LEVEL: 'debug',
  MULTI: 'line one\nline two',
  PORT: '8100'
}
undefined

A .env file usually contains passwords and keys, so add it to .gitignore and commit a .env.example with the variable names and dummy values instead.

Environment variables are strings

Every value in process.env is a string, and assigning to it converts the value to a string. This leads to classic bugs:

process.env.DEBUG = 'false';
process.env.TIMEOUT = '30s';

if (process.env.DEBUG) console.log('debug is on?!');
console.log(Number(process.env.TIMEOUT));
console.log(Number(''));

process.env.PORT = 8000;
console.log(typeof process.env.PORT);
debug is on?!
NaN
0
string

'false' is a non-empty string, so it's truthy. Number() returns NaN for junk and 0 for an empty string. Convert each variable once, in one place, and fail loudly when a value is wrong:

// env.js
export function envString(name, fallback) {
  const v = process.env[name];
  if (v === undefined || v === '') {
    if (fallback === undefined) throw new Error(`missing env variable ${name}`);
    return fallback;
  }
  return v;
}

export function envInt(name, fallback) {
  const v = envString(name, fallback === undefined ? undefined : String(fallback));
  if (!/^-?\d+$/.test(v)) throw new Error(`${name} must be an integer, got "${v}"`);
  return Number(v);
}

export function envBool(name, fallback) {
  const v = envString(name, fallback === undefined ? undefined : String(fallback));
  const s = v.toLowerCase();
  if (['1', 'true', 'yes', 'on'].includes(s)) return true;
  if (['0', 'false', 'no', 'off'].includes(s)) return false;
  throw new Error(`${name} must be a boolean, got "${v}"`);
}
import { envString, envInt, envBool } from './env.js';

process.env.DEBUG = 'false';
process.env.WORKERS = '4';
process.env.TIMEOUT_MS = '30s';

console.log(envBool('DEBUG', false));
console.log(envInt('WORKERS', 1));
console.log(envInt('MAX_BODY', 1048576));
console.log(envString('REGION', 'eu-west-1'));

for (const fn of [() => envInt('TIMEOUT_MS'), () => envString('API_KEY')]) {
  try {
    fn();
  } catch (err) {
    console.log(err.message);
  }
}
false
4
1048576
eu-west-1
TIMEOUT_MS must be an integer, got "30s"
missing env variable API_KEY

YAML

YAML allows comments and is less noisy than JSON, which is why Docker Compose, Kubernetes and GitHub Actions use it. Install the yaml package with npm install yaml. Here is config/app.yaml:

# Application settings
port: 8000
logLevel: info

db:
  host: localhost
  port: 5432
  name: shop

features:
  - search
  - export

# anchors let you reuse a block
defaults: &retry
  retries: 3
  timeoutMs: 2000
payments:
  <<: *retry
  timeoutMs: 5000
import { readFile } from 'node:fs/promises';
import { parse } from 'yaml';

const config = parse(await readFile('config/app.yaml', 'utf8'), { merge: true });
console.log(config.db);
console.log(config.features);
console.log(config.payments);
{ host: 'localhost', port: 5432, name: 'shop' }
[ 'search', 'export' ]
{ retries: 3, timeoutMs: 5000 }

The << merge key isn't part of YAML 1.2, so it's off by default. Without merge: true, payments would contain a literal '<<' key.

YAML guesses types from how values look, which can surprise you:

import { parse } from 'yaml';

const doc = parse(`
version: 1.10
country: NO
zip: 01234
enabled: yes
`);
console.log(doc);

try {
  parse('db:\n  host: localhost\n   port: 5432\n');
} catch (err) {
  console.log(err.name);
  console.log(err.message);
}
{ version: 1.1, country: 'NO', zip: 1234, enabled: 'yes' }
YAMLParseError
Nested mappings are not allowed in compact mappings at line 2, column 9:

  host: localhost
        ^

The version became the number 1.1 and the zip code lost its leading zero. The yaml package uses YAML 1.2 rules, so NO and yes stay strings; YAML 1.1 parsers turn them into booleans. Quote values that must be strings: version: "1.10", zip: "01234". Indentation is part of the syntax, and one extra space is an error.

TOML

TOML looks like INI but has a precise spec with real types, including dates. Rust's Cargo.toml and Python's pyproject.toml use it. smol-toml is a small, spec-compliant parser: npm install smol-toml.

# Application settings
port = 8000
log_level = "info"
started = 2026-10-17T09:00:00Z

[db]
host = "localhost"
port = 5432
name = "shop"

[[upstream]]
name = "billing"
url = "https://billing.internal"

[[upstream]]
name = "search"
url = "https://search.internal"
import { readFile } from 'node:fs/promises';
import { parse, stringify } from 'smol-toml';

const config = parse(await readFile('config/app.toml', 'utf8'));
console.log(config.db);
console.log(config.upstream.map((u) => u.name));
console.log(config.started instanceof Date, config.started.toISOString());

try {
  parse('port = 8000\nport = 9000\n');
} catch (err) {
  console.log(err.message.split('\n')[0]);
}

console.log(stringify({ port: 8000, db: { host: 'localhost' } }));
[Object: null prototype] {
  host: 'localhost',
  port: 5432,
  name: 'shop'
}
[ 'billing', 'search' ]
true 2026-10-17T09:00:00.000Z
Invalid TOML document: trying to redefine an already defined table or value
port = 8000

[db]
host = "localhost"

[[upstream]] defines an array of tables. Strings must be quoted, so there is none of YAML's type guessing, and duplicate keys are an error instead of silently using the last value.

Tables come back as objects with a null prototype. They work like normal objects, but don't have methods such as hasOwnProperty; use Object.hasOwn(obj, key).

INI

INI is the oldest of these formats and has no formal spec. The ini package (npm install ini, the parser npm itself uses for .npmrc) handles the common dialect:

; Application settings
port = 8000
log_level = info

[db]
host = localhost
port = 5432

[features]
search = true
export = false
import { readFile } from 'node:fs/promises';
import ini from 'ini';

const config = ini.parse(await readFile('config/app.ini', 'utf8'));
console.log(config);
console.log(typeof config.db.port, typeof config.features.search);
[Object: null prototype] {
  port: '8000',
  log_level: 'info',
  db: [Object: null prototype] { host: 'localhost', port: '5432' },
  features: [Object: null prototype] { search: true, export: false }
}
string boolean

Only true and false are converted; numbers stay strings, the same as environment variables. Use INI when you have to read an existing INI file, and pick TOML for new ones.

Layering configuration sources

A common pattern merges sources in order, each one overriding the previous:

  1. config/default.json: every setting with a sensible default, committed
  2. config/<environment>.json: differences for production, test and so on, committed
  3. config/local.json: a developer's own overrides, in .gitignore
  4. environment variables: set by the deployment
  5. command-line flags: for one-off runs

Here is config/production.json, which only lists what differs:

{
  "logLevel": "warn",
  "db": { "host": "db.prod.internal" },
  "features": ["search", "export"]
}

The loader needs a deep merge so that overriding db.host keeps db.port and db.name:

// config.js
import { readFileSync, existsSync } from 'node:fs';
import { parseArgs } from 'node:util';

function isPlainObject(v) {
  return typeof v === 'object' && v !== null && !Array.isArray(v);
}

// Objects are merged key by key, everything else (including arrays) is replaced.
function deepMerge(target, source) {
  const out = { ...target };
  for (const [key, value] of Object.entries(source)) {
    if (value === undefined) continue;
    out[key] = isPlainObject(value) && isPlainObject(out[key])
      ? deepMerge(out[key], value)
      : value;
  }
  return out;
}

function readJson(path) {
  if (!existsSync(path)) return {};
  return JSON.parse(readFileSync(path, 'utf8'));
}

function fromEnv(env) {
  return {
    port: env.PORT === undefined ? undefined : Number(env.PORT),
    logLevel: env.LOG_LEVEL,
    db: {
      host: env.DB_HOST,
      port: env.DB_PORT === undefined ? undefined : Number(env.DB_PORT),
    },
  };
}

function fromArgs(argv) {
  const { values } = parseArgs({
    args: argv,
    options: {
      port: { type: 'string' },
      'log-level': { type: 'string' },
    },
  });
  return {
    port: values.port === undefined ? undefined : Number(values.port),
    logLevel: values['log-level'],
  };
}

export function loadConfig({ env = process.env, argv = process.argv.slice(2) } = {}) {
  const appEnv = env.APP_ENV ?? 'development';
  let config = readJson('config/default.json');
  config = deepMerge(config, readJson(`config/${appEnv}.json`));
  config = deepMerge(config, readJson('config/local.json'));
  config = deepMerge(config, fromEnv(env));
  config = deepMerge(config, fromArgs(argv));
  return config;
}
import { loadConfig } from './config.js';

console.log(loadConfig());
$ node ex9.js
{
  port: 8000,
  logLevel: 'info',
  db: { host: 'localhost', port: 5432, name: 'shop' },
  features: [ 'search' ]
}

$ APP_ENV=production DB_PORT=6432 node ex9.js --log-level=error
{
  port: 8000,
  logLevel: 'error',
  db: { host: 'db.prod.internal', port: 6432, name: 'shop' },
  features: [ 'search', 'export' ]
}

Notes:

Validating configuration

A typo in a config file should stop the program at startup with a clear message, not cause a confusing error an hour later. A schema library checks types, fills in defaults and reports every problem at once. With zod (npm install zod):

import { z } from 'zod';

const ConfigSchema = z.object({
  port: z.number().int().min(1).max(65535),
  logLevel: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
  db: z.object({
    host: z.string().min(1),
    port: z.number().int().default(5432),
    name: z.string(),
  }),
  features: z.array(z.string()).default([]),
});

const good = ConfigSchema.parse({
  port: 8000,
  db: { host: 'localhost', name: 'shop' },
});
console.log(good);

const result = ConfigSchema.safeParse({
  port: 70000,
  logLevel: 'verbose',
  db: { host: '' },
});
if (!result.success) {
  console.log(z.prettifyError(result.error));
}
{
  port: 8000,
  logLevel: 'info',
  db: { host: 'localhost', port: 5432, name: 'shop' },
  features: []
}
✖ Too big: expected number to be <=65535
  → at port
✖ Invalid option: expected one of "debug"|"info"|"warn"|"error"
  → at logLevel
✖ Too small: expected string to have >=1 characters
  → at db.host
✖ Invalid input: expected string, received undefined
  → at db.name

In the layered loader, finish with return ConfigSchema.parse(config). In TypeScript, z.infer<typeof ConfigSchema> gives you the config type for free.

By default z.object drops unknown keys. Use z.strictObject instead to reject them, which catches misspelled keys such as "logLevle" that would otherwise be silently ignored.

Making config read-only

Load the config once at startup and pass it around (or export it from one module). To make sure no code changes it later, freeze it recursively. Object.freeze alone is shallow:

function deepFreeze(obj) {
  for (const value of Object.values(obj)) {
    if (typeof value === 'object' && value !== null) deepFreeze(value);
  }
  return Object.freeze(obj);
}

const config = deepFreeze({ port: 8000, db: { host: 'localhost' }, features: ['search'] });

try {
  config.db.host = 'other';
} catch (err) {
  console.log(err.constructor.name + ': ' + err.message);
}
try {
  config.features.push('export');
} catch (err) {
  console.log(err.constructor.name + ': ' + err.message);
}
console.log(config.db.host, config.features);
TypeError: Cannot assign to read only property 'host' of object '#<Object>'
TypeError: Cannot add property 1, object is not extensible
localhost [ 'search' ]

ES modules always run in strict mode, so writes to frozen objects throw. In sloppy-mode CommonJS code they fail silently.

JavaScript config files and finding them

Tools such as ESLint, Vite and Prettier let users write their config as a JavaScript module. This allows comments, computed values and functions, at the cost of running the user's code. A myapp.config.js might look like this:

export default {
  port: Number(process.env.PORT ?? 8000),
  plugins: ['gzip', 'cors'],
  rewrite(url) {
    return url.replace(/^\/old\//, '/new/');
  },
};

Command-line tools usually look for the config file in the current directory and then in each parent directory, so the tool works from anywhere inside a project. Load the file with dynamic import(), which needs a file:// URL for absolute paths on Windows:

// findconfig.js
import { existsSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';

const NAMES = ['myapp.config.js', 'myapp.config.mjs', 'myapp.config.json'];

export function findConfig(startDir = process.cwd()) {
  let dir = resolve(startDir);
  while (true) {
    for (const name of NAMES) {
      const candidate = join(dir, name);
      if (existsSync(candidate)) return candidate;
    }
    const parent = dirname(dir);
    if (parent === dir) return null; // reached the filesystem root
    dir = parent;
  }
}

export async function loadConfigFile(path) {
  if (path.endsWith('.json')) {
    const mod = await import(pathToFileURL(path).href, { with: { type: 'json' } });
    return mod.default;
  }
  const mod = await import(pathToFileURL(path).href);
  return mod.default;
}
import { relative } from 'node:path';
import { findConfig, loadConfigFile } from './findconfig.js';

const path = findConfig('proj/src/deep');
console.log(relative(process.cwd(), path));

const config = await loadConfigFile(path);
console.log(config.port, config.plugins);
console.log(config.rewrite('/old/page'));
proj\myapp.config.js
8000 [ 'gzip', 'cors' ]
/new/page

(On macOS and Linux the first line is proj/myapp.config.js.)

Modules are cached, so importing the same file twice returns the old version. That's fine for a CLI that runs once. A long-running program that needs to reload a JS config can add a query string such as ?t=${Date.now()} to the URL, but each reload leaks the old module, so prefer JSON for config that changes at runtime.

Per-user settings files

Desktop apps and CLI tools often store settings per user. Each OS has a standard place for them:

// settings.js
import { readFile, rename, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';

export function userConfigDir(appName) {
  if (process.platform === 'win32') {
    return join(process.env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), appName);
  }
  if (process.platform === 'darwin') {
    return join(homedir(), 'Library', 'Application Support', appName);
  }
  return join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), appName);
}

export async function readSettings(file, defaults) {
  try {
    return { ...defaults, ...JSON.parse(await readFile(file, 'utf8')) };
  } catch (err) {
    if (err.code === 'ENOENT') return { ...defaults };
    throw err;
  }
}

// Write to a temp file in the same directory, then rename over the original.
// A crash in the middle leaves the old file intact instead of a half-written one.
export async function writeSettings(file, settings) {
  const tmp = `${file}.${process.pid}.tmp`;
  await writeFile(tmp, JSON.stringify(settings, null, 2) + '\n');
  await rename(tmp, file);
}
import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { userConfigDir, readSettings, writeSettings } from './settings.js';

const dir = userConfigDir('myapp');
console.log(dir);

// for the demo, use a local directory instead of the real one
const demoDir = 'demo-settings';
await mkdir(demoDir, { recursive: true });
const file = join(demoDir, 'settings.json');

const defaults = { theme: 'light', recentFiles: [] };
const settings = await readSettings(file, defaults);
console.log('before:', settings);

settings.theme = 'dark';
const opened = 'notes.md';
settings.recentFiles = [opened, ...settings.recentFiles.filter((f) => f !== opened)].slice(0, 5);
await writeSettings(file, settings);

console.log('after:', await readSettings(file, defaults));
C:\Users\alice\AppData\Roaming\myapp
before: { theme: 'light', recentFiles: [] }
after: { theme: 'dark', recentFiles: [ 'notes.md' ] }

On Linux the directory would be /home/alice/.config/myapp. Merging the saved settings over the defaults means a settings file written by an older version still works after you add new settings. The temp-file-and-rename trick is explained in Temporary files.

Reloading when the file changes

Long-running servers can pick up config changes without a restart by watching the file. Two things matter: editors often fire several change events per save, so debounce them, and a half-saved or broken file must not replace a working config:

import { watch } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';

const file = 'live.json';
await writeFile(file, JSON.stringify({ logLevel: 'info' }));

let config = JSON.parse(await readFile(file, 'utf8'));
console.log('loaded', config);

let timer;
const watcher = watch(file, () => {
  // editors often fire several events per save; wait until they settle
  clearTimeout(timer);
  timer = setTimeout(reload, 100);
});

async function reload() {
  try {
    const next = JSON.parse(await readFile(file, 'utf8'));
    config = next;
    console.log('reloaded', config);
  } catch (err) {
    console.log('keeping old config:', err.message);
  }
}

// simulate someone editing the file
await sleep(200);
await writeFile(file, JSON.stringify({ logLevel: 'debug' }));
await sleep(300);
await writeFile(file, '{ "logLevel": ');
await sleep(300);
console.log('current', config);
watcher.close();
loaded { logLevel: 'info' }
reloaded { logLevel: 'debug' }
keeping old config: Unexpected end of JSON input
current { logLevel: 'debug' }

In a real program, validate next with the schema before swapping it in. Code that copied a value out of the config (for example, a port a server is already listening on) won't see the change, so only reload settings that are read each time they are used, like log levels or feature flags. Many deployments skip this and restart the process instead, which is simpler and always consistent.

Node.js's own config file

Node.js 24 can also read its own command-line options from a JSON file. This is experimental:

{
  "$schema": "https://nodejs.org/dist/v24.20.0/docs/node-config-schema.json",
  "nodeOptions": {
    "import": ["./setup.js"],
    "enable-source-maps": true
  }
}
$ node --experimental-config-file=node.config.json app.js
(node:10348) ExperimentalWarning: --experimental-config-file is an experimental feature and might change at any time
setup ran
true

--experimental-default-config-file loads node.config.json from the current directory. Only some options are allowed in the file (V8 flags like --max-old-space-size and --env-file are rejected in Node.js 24), so for now it's mostly useful for shared flags like --import loaders. This file configures Node.js itself, not your app.

Tips

Summary

Task Code
read a JSON file JSON.parse(await readFile(path, 'utf8'))
import JSON import cfg from './cfg.json' with { type: 'json' }
load a .env file at startup node --env-file=.env app.js
optional .env file --env-file-if-exists=.env
load .env from code process.loadEnvFile('.env')
parse .env text without touching process.env util.parseEnv(text)
parse YAML parse(text, { merge: true }) from yaml
parse TOML parse(text) from smol-toml
parse INI ini.parse(text) from ini
parse flags util.parseArgs({ args, options })
validate ConfigSchema.parse(config) with zod
make read-only recursive Object.freeze
load a JS config file await import(pathToFileURL(path).href)
save settings safely write temp file, then rename
watch for changes fs.watch(file, debouncedReload)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents