JAVASCRIPT

Securely Access Environment Variables in Node.js Applications

Learn how to securely retrieve and utilize sensitive configuration data from environment variables in your Node.js applications to avoid hardcoding secrets.

// In a production environment, environment variables are typically set
// through your hosting platform (e.g., Heroku, AWS, Netlify).
// For local development, you might use a package like 'dotenv'
// to load variables from a .env file, but the access method remains the same.

// server.js or app.js
const express = require('express');
const app = express();

// Securely access sensitive configuration data from environment variables
const DATABASE_URL = process.env.DATABASE_URL;
const API_KEY_SECRET = process.env.API_KEY_SECRET;
const PORT = process.env.PORT || 3000; // Provide a default for PORT

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

if (!API_KEY_SECRET) {
  console.warn('Warning: API_KEY_SECRET environment variable is not set. Using a placeholder.');
  // In a real app, you might want to exit or handle this more strictly
  // For demonstration, we'll use a placeholder.
  // API_KEY_SECRET = 'a_default_secret_for_dev_only'; // NOT recommended for production
}

app.get('/', (req, res) => {
  // Avoid exposing sensitive variables directly in responses
  res.send(`App is running on port ${PORT}. Database URL is configured.`);
});

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  // console.log(`Database URL: ${DATABASE_URL ? 'Configured' : 'Not Configured'}`);
  // console.log(`API Key Secret: ${API_KEY_SECRET ? 'Configured' : 'Not Configured'}`);
});

// To run this example locally for testing:
// 1. Set environment variables in your shell:
//    export DATABASE_URL="postgresql://user:pass@host:port/database"
//    export API_KEY_SECRET="your_very_secret_api_key"
// 2. Then run: node server.js
//
// For persistent local development, you'd typically use the `dotenv` package:
// require('dotenv').config(); // at the very top of your entry file
// But the access (`process.env.VARIABLE_NAME`) remains identical.
How it works: This Node.js snippet demonstrates the secure way to access configuration parameters, especially sensitive ones like database credentials or API keys, using environment variables. Instead of hardcoding secrets directly into the application code, `process.env.VARIABLE_NAME` is used to retrieve values set outside the application. This practice prevents sensitive data from being committed to version control systems and allows for easy configuration changes across different deployment environments (development, staging, production) without modifying the codebase. It also includes basic checks for missing critical variables.

Need help integrating this into your project?

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

Hire DigitalCodeLabs