Course contentsShow
← JavaScript
Lesson 1498 of 2,72333. JavaScript in Node.jsFree lesson

Process.env: Environment Variables

Reading environment variables to configure your application without hardcoding values.

Process.env: Environment Variables

You'll learn how to read configuration values from your environment instead of hardcoding them in your code.

What Are Environment Variables?

Think of environment variables like sticky notes on your computer that store configuration information. Instead of writing secrets, API keys, or settings directly into your code files, you store them in the environment where your application runs. Your Node.js program can then read these values at runtime.

process.env is an object containing all environment variables available to your Node.js process. Each key is a variable name, and each value is a string.

Why Use Environment Variables?

Hardcoding values like database passwords or API keys directly in your code is dangerous—anyone with access to your code can see them. Environment variables let you:

  • Keep secrets out of version control
  • Use different configurations for development, testing, and production
  • Change settings without modifying code

Reading Environment Variables

// Access an environment variable
const port = process.env.PORT || 3000;
console.log(`Server will run on port ${port}`);

const apiKey = process.env.API_KEY;
if (!apiKey) {
  console.error('API_KEY is not set!');
  process.exit(1);
}

console.log('Database:', process.env.DATABASE_URL);

Environment variables are always strings. If you need a number or boolean, convert them:

const maxConnections = parseInt(process.env.MAX_CONNECTIONS) || 10;
const debugMode = process.env.DEBUG === 'true';

Key Takeaway: process.env gives you access to environment variables, letting you configure your application securely without hardcoding sensitive values in your source code.