JAVASCRIPT

Securely Manage API Keys in Node.js with Environment Variables

Learn the best practice for protecting sensitive API keys in Node.js applications using environment variables and the popular `dotenv` package to prevent hardcoding.

// 1. Install dotenv: npm install dotenv

// 2. Create a .env file in your project root:
// .env content:
// API_KEY=your_super_secret_api_key_12345
// ANOTHER_API_SECRET=another_secret_value

// 3. Add .env to your .gitignore file to prevent committing secrets:
// .gitignore content:
// .env

// 4. In your Node.js application (e.g., app.js or config.js):
require('dotenv').config();

// Now you can access your environment variables
const myApiKey = process.env.API_KEY;
const anotherSecret = process.env.ANOTHER_API_SECRET;

console.log(`My API Key (should not be undefined): ${myApiKey ? 'Loaded' : 'NOT LOADED - Check .env file and dotenv setup'}`);
console.log(`Another Secret (should not be undefined): ${anotherSecret ? 'Loaded' : 'NOT LOADED'}`);

// Example using an API key in a fetch request:
async function callExternalApi() {
  if (!myApiKey) {
    console.error('API_KEY is not set. Cannot make API call.');
    return;
  }
  try {
    const response = await fetch(`https://api.example.com/data?key=${myApiKey}`); // Use key in URL (less secure for sensitive keys)
    // Or better, pass in headers:
    // const response = await fetch('https://api.example.com/data', {
    //   headers: { 'Authorization': `Bearer ${myApiKey}` }
    // });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log('API Response:', data);
  } catch (error) {
    console.error('Error calling external API:', error);
  }
}

// callExternalApi(); // Uncomment to test
How it works: This snippet illustrates the crucial practice of using environment variables to secure sensitive API keys in Node.js applications. By installing the `dotenv` package, you can load variables defined in a `.env` file into `process.env`. This prevents hardcoding secrets directly into your codebase, which is a major security vulnerability. It's critical to add `.env` to your `.gitignore` file to ensure these secrets are never committed to version control. The example shows how to access these variables and use them in an API request, demonstrating a safer way to handle credentials.

Need help integrating this into your project?

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

Hire DigitalCodeLabs