JAVASCRIPT

Secure Configuration with Environment Variables in Node.js

Learn to manage sensitive data like API keys and database credentials securely in Node.js by utilizing environment variables with the `dotenv` package, keeping them out of source control.

// 1. Install dotenv: npm install dotenv
// 2. Create a .env file in your project root (e.g., .env)
//    DB_HOST=localhost
//    DB_USER=root
//    DB_PASS=mysecurepassword
//    API_KEY=your_secret_api_key_123
// 3. Make sure to add .env to your .gitignore file!

// In your main application file (e.g., app.js or server.js)
require('dotenv').config();

// Access environment variables using process.env
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 NODE_ENV = process.env.NODE_ENV || 'development';

console.log(`Environment: ${NODE_ENV}`);
console.log(`DB Host: ${dbHost}`);
console.log(`DB User: ${dbUser}`);
// console.log(`DB Pass: ${dbPass}`); // Avoid logging sensitive info in production
// console.log(`API Key: ${apiKey}`); // Avoid logging sensitive info in production

// Example usage: Connect to a database (pseudo-code)
// const mysql = require('mysql2');
// const connection = mysql.createConnection({
//     host: dbHost,
//     user: dbUser,
//     password: dbPass
// });
// connection.connect(err => {
//     if (err) throw err;
//     console.log("Successfully connected to database!");
// });

// Remember to never commit your .env file to version control!
How it works: This Node.js snippet demonstrates how to securely manage application configuration, especially sensitive credentials, using environment variables. By leveraging the `dotenv` package, developers can store variables in a `.env` file (which should be excluded from version control via `.gitignore`) and access them via `process.env`. This prevents hardcoding sensitive information directly into source code, enhancing security and facilitating easier configuration management across different deployment environments.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs