JAVASCRIPT

Secure API Key Handling in Node.js

Protect sensitive API keys in Node.js applications by loading them from environment variables, preventing their exposure in source code or client-side bundles.

// Ensure you have a .env file in your root directory with API_KEY=your_secret_key
// Or set the environment variable directly in your hosting environment.
// To use .env file, install 'dotenv' package: npm install dotenv
// require('dotenv').config();

const API_KEY = process.env.EXTERNAL_SERVICE_API_KEY; // e.g., EXTERNAL_SERVICE_API_KEY=sk_test_12345

if (!API_KEY) {
  console.error('EXTERNAL_SERVICE_API_KEY is not set. Please define it in your environment variables.');
  process.exit(1); // Exit if critical API key is missing
}

async function callExternalService(endpoint, data) {
  try {
    const response = await fetch(`https://api.external.com/${endpoint}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}` // Using the API key securely
      },
      body: JSON.stringify(data)
    });

    if (!response.ok) {
      const errorBody = await response.json().catch(() => ({ message: 'Unknown error' }));
      throw new Error(`API call failed: ${response.status} - ${errorBody.message}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Error calling external service:', error.message);
    throw error;
  }
}

// Example Usage (ensure API_KEY is set):
// callExternalService('process-payment', { amount: 100, currency: 'USD' })
//   .then(result => console.log('Payment processed:', result))
//   .catch(err => console.error('Payment failed:', err.message));
How it works: This snippet demonstrates the crucial practice of securing API keys in a Node.js application by loading them from environment variables (e.g., using `process.env`). This prevents sensitive credentials from being committed to version control or exposed in client-side code. The API key is then used in an authenticated request to an external service, ensuring secure communication.

Need help integrating this into your project?

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

Hire DigitalCodeLabs