bhylu.com

Advertisements

Node.js Environment Configuration

Environment values are text. Parse required settings once at startup and reject an invalid deployment configuration before serving requests.

How it works

Use a small configuration function whose input can be a test object rather than the live environment. The example accepts a bounded numeric port and an explicit known mode. Secrets need their own required-field and delivery policies; do not print them when validation fails. Development and production also differ in trust, logging, proxy and resource assumptions, not just one NODE_ENV value.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as configuration.mjs in a separate empty exercises folder and run node configuration.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

configuration.mjs

export function configuration(env) {
  const raw = env.PORT ?? '3000';
  if (!/^[0-9]+$/.test(raw)) throw new Error('Invalid port');
  const port = Number(raw);
  if (!Number.isInteger(port) || port < 1024 || port > 65535)
    throw new Error('Invalid port');
  const mode = env.NODE_ENV ?? 'development';
  if (!['development', 'test', 'production'].includes(mode))
    throw new Error('Invalid mode');
  return { port, mode };
}
console.log(JSON.stringify(configuration({ PORT: '3100', NODE_ENV: 'test' })));
try {
  configuration({ PORT: '3100oops' });
} catch (error) {
  console.log(error.message);
}

Expected result

{"port":3100,"mode":"test"}
Invalid port

The configuration object is small and typed after validation. The parser rejects an ambiguous port rather than letting a networking call discover a different interpretation later. No secret is read or logged by this fixture.

Use the Node.js API reference for the precise version contract.