JAVASCRIPT

Making Authenticated API Calls with Bearer Tokens

Discover how to secure your API requests by adding an Authorization Bearer Token header using the Fetch API for protected endpoints.

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

    if (!response.ok) {
      if (response.status === 401 || response.status === 403) {
        console.error('Authentication failed or unauthorized access.');
        // Potentially redirect to login or refresh token
      }
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error fetching authenticated data:", error);
    throw error;
  }
}

// Example usage:
// const userToken = 'YOUR_JWT_TOKEN_HERE'; // Get this from login/session
// fetchAuthenticatedData('https://api.example.com/user/profile', userToken)
//   .then(profile => console.log('User profile:', profile))
//   .catch(error => console.error('Failed to get profile:', error));
How it works: This snippet illustrates how to include a Bearer Token in the `Authorization` header when making API requests. This is a common method for authenticating users or clients against protected API endpoints. The `fetchAuthenticatedData` function takes a URL and a token, then adds a `Bearer` token to the request headers. It also includes basic error handling, specifically checking for 401 (Unauthorized) or 403 (Forbidden) status codes, which are typical responses for authentication issues.

Need help integrating this into your project?

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

Hire DigitalCodeLabs