JAVASCRIPT

Authenticate API Requests with Bearer Token

Learn how to securely authenticate API requests by adding an Authorization header with a Bearer token using JavaScript's Fetch API for secure communication.

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

    if (!response.ok) {
      if (response.status === 401 || response.status === 403) {
        console.error('Authentication failed or forbidden.');
        // Redirect to login or refresh token
      }
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

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

// Usage example:
// const apiUrl = 'https://api.example.com/data';
// const userToken = 'YOUR_AUTH_TOKEN_HERE'; // In a real app, retrieve securely
// fetchDataWithAuth(apiUrl, userToken)
//   .then(data => console.log('Fetched data:', data))
//   .catch(error => console.error('Failed to fetch:', error));
How it works: This snippet demonstrates how to include an authentication token (specifically a Bearer token) in the `Authorization` header of an API request using JavaScript's Fetch API. It sets the `Content-Type` and then adds the `Authorization: Bearer [token]` header. The code also includes basic error handling for common authentication-related HTTP status codes like 401 (Unauthorized) and 403 (Forbidden), suggesting where to implement re-authentication or token refresh logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs