JAVASCRIPT
Securely Manage Sensitive Credentials with Environment Variables
Learn to secure sensitive information like API keys and database credentials by using environment variables, preventing their exposure in code repositories.
// Install required package: npm install dotenv
require('dotenv').config(); // Load environment variables from .env file
// Accessing environment variables
const DB_HOST = process.env.DB_HOST || 'localhost';
const DB_USER = process.env.DB_USER || 'root';
const DB_PASSWORD = process.env.DB_PASSWORD; // Should not have a default for production
const API_KEY = process.env.THIRD_PARTY_API_KEY;
// Example usage
console.log('Database Host:', DB_HOST);
console.log('Database User:', DB_USER);
// IMPORTANT: Never log sensitive information in production!
// console.log('Database Password:', DB_PASSWORD); // BAD PRACTICE!
// console.log('API Key:', API_KEY); // BAD PRACTICE!
if (DB_PASSWORD && API_KEY) {
console.log('Sensitive credentials loaded successfully.');
// In a real application, you would use these to initialize connections
// or make authenticated API calls.
// Example: connectToDatabase(DB_HOST, DB_USER, DB_PASSWORD);
// Example: makeAuthenticatedApiCall(API_KEY);
} else {
console.warn('Warning: Some sensitive credentials are not set.');
console.warn('Please ensure DB_PASSWORD and THIRD_PARTY_API_KEY are defined in your .env file or environment.');
}
// Example of a .env file (DO NOT COMMIT THIS FILE TO VERSION CONTROL)
// -------------------- .env --------------------
// DB_HOST=your_db_server.com
// DB_USER=my_db_user
// DB_PASSWORD=very_secret_db_password
// THIRD_PARTY_API_KEY=sk_live_XXXXXXXXXXXXXXXXXXXXXXX
// ------------------------------------------------
// Example of a .gitignore entry
// -------------------- .gitignore --------------------
// # Environment variables
// .env
// ----------------------------------------------------
How it works: This Node.js snippet demonstrates the crucial security practice of managing sensitive data, such as database credentials and API keys, using environment variables with the `dotenv` library. Hardcoding such information directly into your codebase is a major security risk, as it can be exposed if your code repository becomes public. By loading these values from a `.env` file (which should be excluded from version control via `.gitignore`), they remain external to the code. This approach ensures that sensitive data is kept confidential across different environments (development, staging, production) and is never committed to source control.