Last modified: May 14, 2026 By Alexander Williams

JavaScript Environment Variables Guide

Environment variables store configuration data outside your code. They keep sensitive info like API keys safe. They also make your app flexible across different environments.

This guide covers everything about JavaScript environment variables. You will learn how to set, read, and manage them. We will use simple examples and clear explanations.

What Are Environment Variables?

Environment variables are dynamic values. They affect how running processes behave on a computer. They are part of the operating system or runtime environment.

In JavaScript, they are especially useful for Node.js apps. They help you store database URLs, secret keys, and port numbers. You never hardcode these values into your source code.

Environment variables keep your code secure and portable. You can change configs without modifying code. This is vital for deploying apps to different servers.

Why Use Environment Variables in JavaScript?

There are many reasons to use them. First, they separate config from code. This follows the 12-factor app methodology.

Second, they protect sensitive data. You never commit API keys or passwords to Git. Instead, you use a .env file in development.

Third, they make testing easier. You can switch between development, staging, and production configs. Just change the variable values.

Setting Environment Variables in Node.js

In Node.js, you access environment variables through the global process.env object. This object holds all environment variables as string key-value pairs.

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

You can set environment variables in your terminal. For example, on Linux or macOS:

export PORT=5000
node app.js

On Windows Command Prompt:

set PORT=5000
node app.js

This is fine for simple cases. But for many variables, you need a better approach.

Using .env Files with dotenv

The dotenv package loads variables from a .env file. This keeps your configs organized and easy to manage.

First, install dotenv:

npm install dotenv

Create a .env file in your project root:

DB_HOST=localhost
DB_USER=admin
DB_PASS=secret123
API_KEY=abc123def456

Then load it in your app:

// Load environment variables from .env file
require('dotenv').config();

const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const apiKey = process.env.API_KEY;

console.log('Database Host:', dbHost);
console.log('Database User:', dbUser);

Output:

Database Host: localhost
Database User: admin

Always add .env to your .gitignore file. This prevents secrets from being pushed to version control.

Environment Variables in the Browser

In browser JavaScript, you cannot access process.env. Browser code runs client-side. You must use build tools to inject environment variables.

With Webpack, use the DefinePlugin. With Vite, use import.meta.env. With Create React App, prefix variables with REACT_APP_.

Example with Vite:

// Access Vite environment variable
const apiUrl = import.meta.env.VITE_API_URL;
console.log('API URL:', apiUrl);

Remember: Never expose sensitive keys to the browser. Environment variables in client code are visible to users. Only use them for non-secret configs like API base URLs.

Best Practices for Environment Variables

Follow these rules to keep your app secure and maintainable.

1. Use descriptive names. Prefix with APP name or section. Example: APP_DB_HOST.

2. Provide default values. Use fallbacks in code. This prevents crashes when variables are missing.

3. Validate required variables. Check at app startup. Throw clear errors if something is missing.

// Validate required environment variables
const requiredVars = ['DB_HOST', 'DB_USER', 'DB_PASS'];
requiredVars.forEach((varName) => {
  if (!process.env[varName]) {
    throw new Error(`Missing required env variable: ${varName}`);
  }
});
console.log('All required variables are set.');

4. Keep .env files out of version control. Add .env to .gitignore. Provide a .env.example file with dummy values.

5. Use different .env files for different environments. Example: .env.development, .env.production.

Common Use Cases

Environment variables are used everywhere in modern JavaScript apps.

Database configuration: Store connection strings and credentials.

Third-party API keys: Keep them out of source code.

Port numbers: Make your app flexible for different hosts.

Feature flags: Enable or disable features without redeploying.

Logging levels: Set debug or error levels based on environment.

Example: Full Node.js App with .env

Let's build a simple Express server using environment variables.

First, install Express and dotenv:

npm install express dotenv

Create .env file:

PORT=4000
NODE_ENV=development
MESSAGE=Hello from env!

Create app.js:

// Load environment variables
require('dotenv').config();

const express = require('express');
const app = express();

// Use env variables with defaults
const port = process.env.PORT || 3000;
const nodeEnv = process.env.NODE_ENV || 'development';
const message = process.env.MESSAGE || 'Default message';

app.get('/', (req, res) => {
  res.send(`${message} (Environment: ${nodeEnv})`);
});

app.listen(port, () => {
  console.log(`Server running on port ${port} in ${nodeEnv} mode`);
});

Run the app:

node app.js

Output:

Server running on port 4000 in development mode

Visit http://localhost:4000 in your browser. You will see the message from your .env file.

Common Mistakes to Avoid

Beginners often make these errors. Avoid them to keep your code clean.

Committing .env files to Git. This exposes secrets. Always use .gitignore.

Hardcoding fallback values. Use variables consistently. Don't mix hardcoded strings with env vars.

Assuming all variables are strings.process.env always returns strings. Convert numbers and booleans manually.

// Convert string to number
const port = parseInt(process.env.PORT, 10) || 3000;

// Convert string to boolean
const isDebug = process.env.DEBUG === 'true';

Loading dotenv after using process.env. Always load dotenv at the very top of your entry file.

Conclusion

JavaScript environment variables are essential for secure and flexible apps. They separate configuration from code. They protect sensitive data. They make your app adaptable to different environments.

Use process.env in Node.js. Use .env files with dotenv for development. For browsers, use build tools with proper prefixes. Always follow best practices like validation and gitignore.

Now you can manage environment variables like a pro. Start using them in your next JavaScript project. Your code will be cleaner, safer, and more portable.

For more on variable basics, check our JavaScript Variables Guide. Learn about Types of JavaScript Variables and JavaScript Variable Scope Explained for deeper understanding.