0
0
NodejsHow-ToBeginner · 3 min read

How to Use process.env in Node.js for Environment Variables

In Node.js, you access environment variables using process.env, which is an object containing all environment variables as strings. You can read variables like process.env.VARIABLE_NAME to configure your app without hardcoding values.
📐

Syntax

process.env is a global object in Node.js that holds environment variables as key-value pairs. You access a variable by its name as a property, for example, process.env.PORT. All values are strings or undefined if the variable is not set.

This lets you keep sensitive or environment-specific data outside your code.

javascript
const port = process.env.PORT;
console.log('Server will run on port:', port);
Output
Server will run on port: undefined
💻

Example

This example shows how to read an environment variable MY_SECRET and print it. You can set the variable before running the script.

javascript
console.log('My secret is:', process.env.MY_SECRET);
Output
My secret is: supersecret123
⚠️

Common Pitfalls

  • Environment variables are always strings; convert them if needed (e.g., numbers or booleans).
  • Accessing a variable that is not set returns undefined, which can cause errors if not handled.
  • Setting environment variables depends on your OS and shell; forgetting to set them or setting them incorrectly is a common mistake.
  • Do not commit sensitive environment variables to version control; use .env files with libraries like dotenv for local development.
javascript
/* Wrong way: assuming a number without conversion */
const timeout = process.env.TIMEOUT;
console.log(timeout + 1000); // This will concatenate strings, not add numbers

/* Right way: convert string to number */
const timeoutNum = Number(process.env.TIMEOUT);
console.log(timeoutNum + 1000);
Output
10001000 2000
📊

Quick Reference

Tips for using process.env effectively:

  • Use uppercase names with underscores for environment variables (e.g., DB_HOST).
  • Check if variables exist before using them to avoid errors.
  • Use libraries like dotenv to load variables from a file during development.
  • Remember all values are strings; convert as needed.

Key Takeaways

Use process.env.VARIABLE_NAME to access environment variables as strings in Node.js.
Always check if a variable exists to avoid undefined errors.
Convert environment variable strings to the needed type before use.
Use .env files and libraries like dotenv for local environment management.
Never hardcode sensitive data; keep it in environment variables.