JAVASCRIPT
Manage Sensitive API Keys Using Environment Variables in Node.js
Learn to safeguard your application's sensitive information, like API keys, by storing them in environment variables instead of hardcoding them into your Node.js code.
// In package.json, add a script like: "start": "node -r dotenv/config server.js"
// Or install 'dotenv' (npm install dotenv) and add 'require('dotenv').config();' at the top of your main file.
//
// .env file content (this file should NOT be committed to version control!)
// API_KEY=your_super_secret_api_key_12345
// DB_HOST=localhost
// DB_USER=admin
// In your main application file (e.g., server.js)
require('dotenv').config(); // Load environment variables from .env file
const express = require('express');
const app = express();
const MY_API_KEY = process.env.API_KEY;
const DB_HOST = process.env.DB_HOST;
const DB_USER = process.env.DB_USER;
if (!MY_API_KEY) {
console.error("CRITICAL ERROR: API_KEY not found in environment variables. Please set it.");
process.exit(1);
}
app.get('/api/data', (req, res) => {
// In a real scenario, you'd use MY_API_KEY to authenticate with an external service
// For demonstration, we just return a message.
res.json({
message: 'Data accessed securely',
apiKeyUsed: MY_API_KEY ? '******' + MY_API_KEY.slice(-4) : 'N/A',
dbInfo: `Connected to ${DB_HOST} as ${DB_USER}`
});
});
app.listen(3000, () => {
console.log(`Server running on port 3000. Accessing API key safely.`);
});
// To run:
// 1. Create a .env file in the same directory as server.js with content: API_KEY=your_secret_key
// 2. npm install express dotenv
// 3. node server.js
// Or if using the package.json script: npm start (after setting up the script)
How it works: This Node.js snippet demonstrates the secure practice of managing sensitive information like API keys using environment variables. Instead of hardcoding credentials directly into your source code, which poses a significant security risk if the code is exposed, `dotenv` loads variables from a `.env` file into `process.env`. This allows you to keep production secrets out of version control systems (like Git) and manage them independently for different deployment environments. Accessing them via `process.env.VARIABLE_NAME` ensures they are never directly exposed in the codebase.