JAVASCRIPT

Securely Fetch Data with API Key Authentication

Learn to make authenticated GET requests to an API using an API key in the request headers, essential for securing data access in web applications.

async function fetchDataWithApiKey(url, apiKey) {
  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}` // Common for JWT, or 'x-api-key' for direct API keys
      }
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message || response.statusText}`);
    }

    const data = await response.json();
    console.log('Fetched data:', data);
    return data;
  } catch (error) {
    console.error('Error fetching data:', error.message);
    throw error; // Re-throw to allow further handling
  }
}

// Example Usage:
// const MY_API_KEY = 'YOUR_SECRET_API_KEY'; // In a real app, load this securely (e.g., environment variables)
// fetchDataWithApiKey('https://api.example.com/data', MY_API_KEY)
//   .then(data => console.log('Successfully received:', data))
//   .catch(error => console.error('Failed to fetch:', error));
How it works: This snippet demonstrates how to make an authenticated GET request to an API using a shared API key. The key is typically sent in the `Authorization` header, often prefixed with 'Bearer' for token-based authentication or sometimes as a custom header like 'x-api-key'. It also includes basic error handling for non-successful HTTP responses, parsing error messages from the response body when available.

Need help integrating this into your project?

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

Hire DigitalCodeLabs