JAVASCRIPT
Best Practice for Secure API Key Management in Node.js
Learn how to securely store and access sensitive API keys and credentials using environment variables in your Node.js applications.
// .env file (DO NOT commit to version control)
// MY_API_KEY=your_super_secret_api_key_12345
// DATABASE_URL=mongodb://localhost:27017/mydb
// In your Node.js application (e.g., app.js)
require('dotenv').config(); // Make sure to install: npm install dotenv
const myApiKey = process.env.MY_API_KEY;
const databaseUrl = process.env.DATABASE_URL;
if (!myApiKey || !databaseUrl) {
console.error('CRITICAL: Missing environment variables! Check .env file or deployment config.');
process.exit(1);
}
console.log('API Key loaded successfully (but not displayed directly):', myApiKey ? '*****' : 'N/A');
console.log('Database URL loaded successfully (but not displayed directly):', databaseUrl ? '*****' : 'N/A');
// Example usage:
// const apiCall = new MyApiClient(myApiKey);
// database.connect(databaseUrl);
How it works: Sensitive information like API keys, database credentials, and other secrets should never be hardcoded directly into your application's source code or committed to version control. Using environment variables (e.g., via a `.env` file in development and platform-specific configurations in production) provides a secure way to manage these secrets. The `dotenv` package for Node.js helps load these variables during development, while production environments typically provide native support for setting them.