Table of Contents
- Introduction to Environment Variables
- Accessing Environment Variables with
process.env
- Using the
dotenv
Package - Security Best Practices
Introduction to Environment Variables
Environment variables are dynamic key-value pairs that provide configuration information to applications. They’re stored outside your application’s code, offering several key advantages:
- Security: Sensitive data like API keys and passwords should never be hardcoded. Environment variables provide a secure way to manage these secrets.
- Flexibility: Easily change application behavior without modifying the codebase. This is crucial for different deployment environments (development, staging, production).
- Portability: Adapt your application to various environments by adjusting environment variables without code changes.
This guide demonstrates how to access environment variables in JavaScript, focusing on Node.js environments.
Accessing Environment Variables with process.env
Node.js provides built-in access to environment variables through the process.env
object. This is the most common and recommended approach for production environments.
// Get a specific environment variable
const apiKey = process.env.API_KEY;
// Check if an environment variable exists and provide a default value
const port = process.env.PORT || 3000;
// Access multiple variables
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
};
//Example of handling missing environment variables with a more descriptive error message
if (!dbConfig.host) {
throw new Error("Database host not configured. Please set the DB_HOST environment variable.");
}
console.log("API Key:", apiKey);
console.log("Port:", port);
console.log("Database Config:", dbConfig);
Remember that setting environment variables is operating system-specific. On Linux/macOS, use export
(e.g., export API_KEY="your_api_key"
); on Windows, use set
.
Using the dotenv
Package
For development, the dotenv
package simplifies managing environment variables from a .env
file. This keeps sensitive information out of your version control system.
- Installation:
npm install dotenv
- .env File: Create a
.env
file (add it to your.gitignore
!) in your project’s root directory:
API_KEY=your_api_key
DATABASE_URL=your_database_url
PORT=3001
- Usage:
require('dotenv').config();
const apiKey = process.env.API_KEY;
const databaseUrl = process.env.DATABASE_URL;
const port = process.env.PORT;
console.log("API Key:", apiKey);
console.log("Database URL:", databaseUrl);
console.log("Port:", port);
dotenv.config()
loads variables from .env
into process.env
. Always prioritize system environment variables over .env
for production deployments.
Security Best Practices
- Never hardcode sensitive information. Always use environment variables.
- Add
.env
to your.gitignore
. Prevent accidental commits of sensitive data. - Use a secrets management solution for production environments to securely store and access sensitive data.
- Validate and sanitize all environment variables before using them in your application to prevent vulnerabilities.
- Regularly review and update your security practices.