JAVASCRIPT
Securely Accessing API Keys in Node.js using Environment Variables
Learn to protect sensitive API keys in Node.js applications by storing them in environment variables, enhancing security and manageability.
const dotenv = require('dotenv');
// Load environment variables from .env file if in development
// For production, environment variables are typically set directly on the server
if (process.env.NODE_ENV !== 'production') {
dotenv.config();
}
// Access your API key securely
const MY_API_KEY = process.env.MY_API_KEY;
const ANOTHER_SERVICE_KEY = process.env.ANOTHER_SERVICE_KEY;
if (!MY_API_KEY) {
console.error('Error: MY_API_KEY environment variable is not set.');
process.exit(1);
}
// Example of how you might use the API key
async function callExternalApi() {
try {
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': `Bearer ${MY_API_KEY}` // Common way to use API keys
// Or 'x-api-key': MY_API_KEY
}
});
const data = await response.json();
console.log('API response:', data);
} catch (error) {
console.error('Failed to call API:', error);
}
}
// Only run the example function if the key is available
if (MY_API_KEY) {
// callExternalApi();
console.log('API Key loaded successfully (but not displayed for security).');
}
// For demonstration: simulate a .env file content
// --- Content of your .env file (DO NOT COMMIT THIS FILE) ---
// MY_API_KEY=your_super_secret_api_key_12345
// ANOTHER_SERVICE_KEY=another_secret_key_67890
How it works: This Node.js snippet demonstrates the best practice for securely handling API keys by storing them in environment variables. It uses the `dotenv` package (for development) to load variables from a `.env` file, ensuring sensitive information is not hardcoded or committed to version control. In production, these variables are typically set directly on the server. Accessing them via `process.env.YOUR_KEY_NAME` keeps your credentials secure and decoupled from your codebase, improving security and deployability.