How to read environment variables in Node.js

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.

Steps to read environment variables in Node.js:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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