JAVASCRIPT

Authenticated GET Request with Bearer Token in JavaScript

Learn to make secure API GET requests using JavaScript's Fetch API, including how to pass an Authorization Bearer token header for authentication.

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

    if (!response.ok) {
      // Handle HTTP errors, e.g., 401, 403, 404
      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('Data fetched successfully:', data);
    return data;
  } catch (error) {
    console.error('Error fetching data:', error.message);
    throw error; // Re-throw to allow caller to handle
  }
}

// Example usage:
// const apiUrl = 'https://api.example.com/secured-data';
// const userToken = 'YOUR_AUTH_BEARER_TOKEN';
// fetchData(apiUrl, userToken)
//   .then(data => console.log('Processed data:', data))
//   .catch(err => console.error('Failed to get data:', err));
How it works: This snippet demonstrates how to perform an authenticated GET request using JavaScript's `fetch` API. It includes setting the `Authorization` header with a `Bearer` token, which is a common authentication method for REST APIs. The code also incorporates basic error handling for network issues and HTTP status codes, parsing the response JSON or throwing an informative error.

Need help integrating this into your project?

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

Hire DigitalCodeLabs