Node.js
Validate numeric environment variables
Environment variables arrive as strings or undefined. Validate a complete value and its allowed range before using it as a port, timeout, or worker count.
Worked example
Node.js example · save as example.mjs and run node example.mjs
function readPort(raw = "3000") {
if (!/^\d+$/.test(raw)) throw new Error("Invalid port");
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535)
throw new Error("Port outside range");
return port;
}
console.log(readPort("8080"));
console.log(readPort(undefined));How it works
The helper rejects suffixes and fractional forms before numeric conversion. The range check encodes an application decision about acceptable ports. In a real process, pass process.env.PORT to the helper and fail early if the configuration is malformed.
Limits and mistakes
Do not log the entire environment during debugging; it can contain credentials. A fallback should apply only when configuration is absent, not when an invalid supplied value deserves an error. Whether port zero is allowed depends on your application.
Check the result
Expect 8080 and 3000. Test an empty string, 70000, and 8080abc. They should be rejected rather than partially parsed or silently defaulted.
Sources
Reference documentation for the behavior used in this guide: