CodingNeed.

1 · Structure and rendering · 30 MIN

Modules and validated configuration

Configuration is input and should be checked before use.

ES modules use explicit imports and exports. Environment variables arrive as strings or undefined, so Number alone is insufficient validation: an empty string becomes zero, and an invalid string becomes NaN. This example accepts only integer ports in the permitted TCP range. Reading configuration in one place makes mistakes fail early and keeps business functions independent of process.env. Do not log an entire environment object because it may contain database passwords and API keys.

Check 1 and 65535.

Read the example

// config.mjs
export function readPort(raw='3000') {
  if(!/^\d+$/.test(raw)) throw new Error('PORT must be an integer');
  const port=Number(raw);
  if(port<1||port>65535)throw new Error('PORT outside allowed range');
  return port;
}
console.log(readPort());
console.log(readPort('8080'));
Check the expected output
3000
8080

Your challenge

Create a separate app.mjs that imports readPort and validates process.env.PORT once during startup.

Solution cost: O(m) validation for m characters. time · O(1) additional scalar state. space

Common trap

A fallback using Number(raw) || 3000 silently turns invalid configuration into a different configuration.

Study the project implementation
// config.mjs
export function readPort(raw='3000') {
  if(!/^\d+$/.test(raw)) throw new Error('PORT must be an integer');
  const port=Number(raw);
  if(port<1||port>65535)throw new Error('PORT outside allowed range');
  return port;
}
console.log(readPort());
console.log(readPort('8080'));

Further reading: Official documentation

Next lesson: Files, paths and resource boundaries

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.