Applications often need deployment-specific settings without baking them into JavaScript source. Node.js inherits environment variables from the shell, service manager, CI job, or container and exposes them through process.env.
Each process.env entry is a string when present, while an absent key evaluates to undefined. An empty assignment produces an empty string instead, so a required setting should reject both states before the program uses it.
A command-scoped APP_PORT assignment in a POSIX-compatible shell lasts only for that Node.js process. APP_PORT carries a non-secret port value here; credentials should be checked for presence without writing their contents to logs.
Related: How to load a .env file in Node.js
Related: How to call an API with fetch in Node.js
Steps to read environment variables in Node.js:
- Create read-env.mjs with a direct APP_PORT lookup.
- read-env.mjs
const port = process.env.APP_PORT; console.log(`Application port: ${port}`);
process.env uses the environment variable name as the object key and returns its value as a string.
- Run the script with APP_PORT set for this process.
$ APP_PORT=8080 node read-env.mjs Application port: 8080
The assignment prefix applies only to this command in a POSIX-compatible shell and does not change the parent shell.
- Add a guard for unset and zero-length APP_PORT values.
- read-env.mjs
const port = process.env.APP_PORT; if (port === undefined || port === "") { console.error("APP_PORT is required"); process.exitCode = 1; } else { console.log(`Application port: ${port}`); }
Setting process.exitCode to 1 lets shells, CI jobs, and service managers detect the invalid configuration after the script finishes.
- Run the guarded script with APP_PORT removed from its command environment by env -u.
$ env -u APP_PORT node read-env.mjs APP_PORT is required
The process exits with status 1 even when the parent shell exports APP_PORT. An explicit empty assignment such as APP_PORT= follows the same failure path.
- Run the guarded script with APP_PORT set to confirm the completed program still reads the configured value.
$ APP_PORT=8080 node read-env.mjs Application port: 8080
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.