0
0
NodejsHow-ToBeginner · 4 min read

How to Use Environment Variables in Production in Node.js

In Node.js production, use process.env to access environment variables set outside your code, typically via your hosting platform or a .env file loaded with dotenv. Never hardcode secrets; instead, set them securely in your server or deployment environment and access them with process.env.VARIABLE_NAME.
📐

Syntax

Environment variables in Node.js are accessed using the process.env object. Each variable is a property on this object, accessed by its name as a string.

  • process.env.VARIABLE_NAME: Gets the value of the environment variable named VARIABLE_NAME.
  • Variables are strings or undefined if not set.
  • Set variables outside your code, e.g., in your server or deployment platform.
javascript
console.log(process.env.PORT);
console.log(process.env.DB_PASSWORD);
Output
3000 mysecretpassword
💻

Example

This example shows how to use the dotenv package to load environment variables from a .env file in production-like setup. It prints the port and database password from environment variables.

javascript
import dotenv from 'dotenv';
dotenv.config();

const port = process.env.PORT || 3000;
const dbPassword = process.env.DB_PASSWORD;

console.log(`Server will run on port: ${port}`);
console.log(`Database password is: ${dbPassword}`);
Output
Server will run on port: 8080 Database password is: supersecret123
⚠️

Common Pitfalls

Not setting environment variables in production: Your app will get undefined values causing errors.

Hardcoding secrets in code: This risks exposing sensitive data if code is shared.

Forgetting to load .env in production: Use dotenv only in development; in production, set variables directly in the environment.

javascript
/* Wrong way: hardcoding secret */
const dbPassword = 'hardcodedpassword';

/* Right way: use environment variable */
const dbPassword = process.env.DB_PASSWORD;

/* Wrong way: relying on .env in production */
import dotenv from 'dotenv';
dotenv.config(); // Avoid this in production, set env vars in server instead
📊

Quick Reference

  • Use process.env.VARIABLE_NAME to access variables.
  • Set environment variables securely in your hosting or server environment.
  • Use dotenv only for local development.
  • Never commit secrets to source code.
  • Check for undefined variables and provide defaults if needed.

Key Takeaways

Always access environment variables in Node.js using process.env.VARIABLE_NAME.
Set environment variables securely outside your code in production environments.
Use the dotenv package only for local development, not in production.
Never hardcode secrets or sensitive data in your source code.
Provide fallback defaults or error handling for missing environment variables.