JAVASCRIPT

Securely Managing Sensitive Configuration with Environment Variables

Protect sensitive API keys, database credentials, and other configurations by using environment variables in Node.js applications, enhancing security.

// For local development, you might use a .env file and 'dotenv' package (npm install dotenv)
// In production, environment variables are set directly on the server/hosting platform.

require('dotenv').config(); // Load environment variables from .env file

const DATABASE_URL = process.env.DATABASE_URL;
const API_KEY = process.env.API_KEY;
const JWT_SECRET = process.env.JWT_SECRET;
const NODE_ENV = process.env.NODE_ENV || 'development';

console.log('Application Environment:', NODE_ENV);

if (!DATABASE_URL) {
  console.error('Error: DATABASE_URL environment variable is not set!');
  process.exit(1);
}

if (!API_KEY) {
  console.warn('Warning: API_KEY environment variable is not set. Some features may fail.');
}

// Use these variables in your application logic
console.log('Database URL (masked for security):', DATABASE_URL ? '*****' + DATABASE_URL.slice(-5) : 'Not Set');
console.log('API Key (masked for security):', API_KEY ? '*****' + API_KEY.slice(-5) : 'Not Set');
console.log('JWT Secret (masked for security):', JWT_SECRET ? '*****' + JWT_SECRET.slice(-5) : 'Not Set');

// Example of how to access them securely within a module
module.exports = {
  dbUrl: DATABASE_URL,
  apiKey: API_KEY,
  jwtSecret: JWT_SECRET,
  isProduction: NODE_ENV === 'production',
};
How it works: This Node.js snippet demonstrates the critical practice of managing sensitive configuration data (like database URLs, API keys, or secrets) using environment variables. Instead of hardcoding these values or committing them to version control, environment variables are set outside the application code. This prevents accidental exposure of credentials, especially in source control, and allows easy configuration changes across different deployment environments (development, staging, production) without modifying the application's codebase.

Need help integrating this into your project?

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

Hire DigitalCodeLabs