JAVASCRIPT

Securely Authenticating API Requests with API Keys in Node.js

Learn to securely add an API key to outgoing HTTP requests in Node.js, typically by including it in the request headers or query parameters.

const fetch = require('node-fetch'); // Requires node-fetch package for Node.js environments

async function fetchDataWithApiKey(url, apiKey, location = 'header') {
  let options = {
    method: 'GET', // Or 'POST', 'PUT', etc.
    headers: {
      'Content-Type': 'application/json',
      // ... other headers
    },
  };

  if (location === 'header') {
    options.headers['X-API-KEY'] = apiKey; // Common header name, check API docs
  } else if (location === 'query') {
    const urlObj = new URL(url);
    urlObj.searchParams.append('apiKey', apiKey); // Common query param name, check API docs
    url = urlObj.toString();
  } else {
    throw new Error('Invalid API Key location. Must be "header" or "query".');
  }

  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Failed to fetch data:', error);
    throw error;
  }
}

// Example Usage:
const MY_API_KEY = process.env.EXTERNAL_API_KEY || 'YOUR_SECURE_API_KEY_HERE'; // Use environment variables!
const API_ENDPOINT = 'https://api.example.com/data'; // Replace with actual API endpoint

// Fetch with API key in header
fetchDataWithApiKey(API_ENDPOINT, MY_API_KEY, 'header')
  .then(data => console.log('Data from header auth:', data))
  .catch(error => console.error('Error fetching data (header auth):', error.message));

// // Example: Fetch with API key in query parameter (if API supports it)
// const QUERY_API_ENDPOINT = 'https://api.example.com/querydata';
// fetchDataWithApiKey(QUERY_API_ENDPOINT, MY_API_KEY, 'query')
//   .then(data => console.log('Data from query auth:', data))
//   .catch(error => console.error('Error fetching data (query auth):', error.message));
How it works: This Node.js snippet demonstrates how to make authenticated API requests using an API key. It provides a flexible `fetchDataWithApiKey` function that can append the API key either as a custom HTTP header (e.g., `X-API-KEY`) or as a query parameter in the URL, depending on the target API's specification. It emphasizes the importance of storing API keys securely, preferably using environment variables (`process.env`), and includes basic error handling for network requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs