JAVASCRIPT
Managing Sensitive Data with Environment Variables
Securely store and access sensitive application data like API keys and database credentials using environment variables with Node.js and `dotenv`.
// Install: npm install dotenv
// In your main application file (e.g., app.js or server.js), at the very top:
require('dotenv').config();
// Example .env file (DO NOT commit to version control!)
// DB_HOST=localhost
// DB_USER=myuser
// DB_PASS=mypassword
// API_KEY=your_super_secret_api_key_123
// NODE_ENV=development
const express = require('express');
const app = express();
// Accessing environment variables
const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASS;
const apiKey = process.env.API_KEY;
const nodeEnv = process.env.NODE_ENV;
console.log(`Database Host: ${dbHost}`);
console.log(`Database User: ${dbUser}`);
// console.log(`Database Password: ${dbPass}`); // Avoid logging sensitive info in production
console.log(`API Key: ${apiKey ? 'Loaded' : 'Not Loaded'}`);
console.log(`Node Environment: ${nodeEnv}`);
app.get('/', (req, res) => {
res.send(`Hello from ${nodeEnv} environment!`);
});
const PORT = process.env.PORT || 3003;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to manage sensitive data using environment variables in a Node.js application with the `dotenv` package. Storing credentials and API keys directly in source code is a major security risk. Environment variables allow you to keep this sensitive information separate from your codebase, preventing it from being accidentally committed to version control. The `dotenv` package loads variables from a `.env` file into `process.env`, making them accessible within your application while keeping them out of the public eye.