JAVASCRIPT

Securely Managing Environment Variables in Web Applications

Learn to securely manage sensitive configuration data using environment variables, ensuring API keys and credentials are not hardcoded or exposed.

// In a real application, create a .env file in the root directory:
// DB_HOST=localhost
// DB_USER=myuser
// DB_PASS=supersecretpassword
// API_KEY=anothersecretkey
// NODE_ENV=development

// index.js or app.js
require('dotenv').config(); // Load environment variables from .env file

const express = require('express');
const app = express();

// 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 nodeEnv = process.env.NODE_ENV || 'development'; // Provide a fallback

if (!dbHost || !dbUser || !dbPass || !apiKey) {
  console.error('Missing one or more critical environment variables!');
  // In a production scenario, you might want to exit the process
  // process.exit(1);
}

app.get('/config', (req, res) => {
  // For demonstration, but typically sensitive info wouldn't be exposed directly
  res.json({
    environment: nodeEnv,
    databaseUser: dbUser,
    // NEVER expose actual passwords or API keys like this in a real API response
    // This is purely for demonstrating that the variables are loaded.
    // apiKeyLast4: apiKey ? apiKey.slice(-4) : 'N/A' // Safer way to hint presence
  });
});

app.get('/', (req, res) => {
    res.send('Check /config endpoint (but be careful with exposing sensitive data in real apps!)');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running in ${nodeEnv} mode on port ${PORT}`);
});
How it works: This snippet demonstrates the best practice of managing sensitive configuration data using environment variables in a Node.js application, typically with the `dotenv` library. Instead of hardcoding credentials (like database passwords or API keys) directly in the code, they are stored in a `.env` file (which should be excluded from version control, e.g., via `.gitignore`). The `dotenv` package loads these variables into `process.env`, allowing the application to access them at runtime. This approach enhances security by separating sensitive configurations from the codebase and preventing their accidental exposure in public repositories.

Need help integrating this into your project?

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

Hire DigitalCodeLabs