JAVASCRIPT

Dynamically Attaching Custom Headers to API Requests

Learn to programmatically add and modify custom HTTP headers to `fetch` API requests in JavaScript, useful for passing dynamic context like tenant IDs, language preferences, or tracing information.

const API_ENDPOINT = 'https://api.your-service.com/data';

/**
 * Fetches data from an API with dynamic custom headers.
 * @param {string} url The API endpoint URL.
 * @param {object} customHeaders An object containing key-value pairs for custom headers.
 * @returns {Promise<object>} The JSON response from the API.
 */
async function fetchDataWithCustomHeaders(url, customHeaders = {}) {
  // Default headers, e.g., for JSON content type or an existing authorization token
  const defaultHeaders = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer your_static_token` // Replace with a dynamic token if applicable
  };

  // Merge default headers with custom headers. Custom headers will override defaults.
  const headers = { ...defaultHeaders, ...customHeaders };

  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: headers
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`API call failed: ${response.status} ${response.statusText} - ${JSON.stringify(errorData)}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Error fetching data with custom headers:', error);
    throw error;
  }
}

// Example Usage 1: Fetching with a tenant ID header
fetchDataWithCustomHeaders(API_ENDPOINT, {
  'X-Tenant-ID': 'my-company-tenant-123',
  'Accept-Language': 'en-US'
}).then(data => {
  console.log('Data for tenant:', data);
}).catch(error => {
  console.error('Failed to get tenant data:', error);
});

// Example Usage 2: Fetching with a correlation ID for tracing
fetchDataWithCustomHeaders(API_ENDPOINT + '/status', {
  'X-Correlation-ID': `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}).then(data => {
  console.log('Status data with correlation ID:', data);
}).catch(error => {
  console.error('Failed to get status data:', error);
});
How it works: This JavaScript snippet illustrates how to dynamically add or override HTTP headers when making API requests using the `fetch` API. It defines a reusable function `fetchDataWithCustomHeaders` that takes a URL and an object of custom headers. These custom headers are merged with any default headers (like `Content-Type` or `Authorization`), allowing for flexible modification of request metadata. This is useful for passing context-specific information to the API, such as tenant identifiers, user preferences, or tracing IDs for distributed systems.

Need help integrating this into your project?

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

Hire DigitalCodeLabs