JAVASCRIPT

Making Authenticated API Requests with Bearer Token

Learn how to securely make API requests by including an Authorization Bearer token in the request headers using JavaScript's Fetch API.

async function fetchAuthenticatedData(url, token) {
  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

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

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching authenticated data:', error);
    throw error; // Re-throw for further handling
  }
}

// Example usage:
// const authToken = 'YOUR_BEARER_TOKEN';
// const apiUrl = 'https://api.example.com/protected-resource';
// fetchAuthenticatedData(apiUrl, authToken)
//   .then(data => console.log('Fetched data:', data))
//   .catch(error => console.error('Failed to fetch:', error));
How it works: This snippet demonstrates how to send an authenticated GET request to an API using the Fetch API. It constructs the `headers` object to include an `Authorization` header with a `Bearer` token. Proper error handling is included to check `response.ok` and parse potential error messages from the API response body, making the request more robust. This is a fundamental pattern for interacting with most secure RESTful APIs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs