← Back to all snippets
JAVASCRIPT

Secure API Requests with Bearer Token

Learn to make authenticated API requests by attaching a Bearer token to the Authorization header, essential for securely accessing protected API resources.

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

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Fetched data:', data);
    return data;
  } catch (error) {
    console.error('Error fetching data with authentication:', error);
    throw error;
  }
}

// Example usage:
// const apiUrl = 'https://api.example.com/protected-data';
// const userToken = 'YOUR_AUTH_TOKEN_HERE'; // Get this from localStorage, session, etc.
// fetchDataWithAuth(apiUrl, userToken)
//   .then(data => console.log('Successfully retrieved:', data))
//   .catch(error => console.error('Failed to retrieve:', error));
How it works: This JavaScript snippet demonstrates how to make authenticated API requests using a Bearer token. The token, typically obtained after a user logs in, is included in the Authorization header of the HTTP request. This method is crucial for accessing protected resources on an API, ensuring that only authenticated and authorized users can retrieve or modify sensitive data. It uses `fetch` for network requests and includes basic error handling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs