JAVASCRIPT

Making Authenticated API Requests with a Bearer Token

Learn to securely integrate APIs by including a Bearer token in your `fetch` requests, a common method for authenticating users or applications.

async function fetchAuthenticatedData(url, token) {
  try {
    const response = await fetch(url, {
      method: 'GET', // Can be POST, PUT, DELETE etc.
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json' // Often required even for GETs
      },
    });

    if (!response.ok) {
      const errorDetails = await response.json().catch(() => ({ message: 'Authentication failed or other API error' }));
      throw new Error(`HTTP error! Status: ${response.status}, Details: ${JSON.stringify(errorDetails)}`);
    }

    const data = await response.json();
    console.log('Authenticated Data:', data);
    return data;
  } catch (error) {
    console.error('Error fetching authenticated data:', error);
    throw error;
  }
}

// Example usage:
// const userToken = 'YOUR_AUTH_BEARER_TOKEN_HERE'; // Get this from localStorage, session, or OAuth flow
// fetchAuthenticatedData('https://api.example.com/protected/resource', userToken)
//   .then(data => console.log('Protected resource data:', data))
//   .catch(err => console.error('Access denied or other issue:', err));
How it works: This snippet demonstrates how to make API requests that require authentication using a Bearer token. The token is included in the `Authorization` header of the `fetch` request, prefixed with "Bearer ". This is a widely used method for authenticating users or applications with RESTful APIs, ensuring secure access to protected resources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs