JAVASCRIPT

Authenticate API Requests with JWT Bearer Token

Understand how to securely attach a JSON Web Token (JWT) in the `Authorization` header of your API requests as a Bearer token for authentication and access control.

async function makeAuthenticatedApiCall(url, method = 'GET', data = null, jwtToken) {
  if (!jwtToken) {
    throw new Error('JWT token is required for authenticated API calls.');
  }

  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${jwtToken}` // Crucial for JWT authentication
  };

  const options = {
    method: method,
    headers: headers,
    body: data ? JSON.stringify(data) : undefined
  };

  try {
    const response = await fetch(url, options);

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`API call failed: ${response.status} - ${errorText}`);
    }

    return response.json();
  } catch (error) {
    console.error('Error making authenticated API call:', error);
    throw error;
  }
}

// Example usage (assuming you have a JWT token, e.g., from a login):
// const USER_JWT = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'; // Replace with actual JWT
// const API_URL = 'https://api.example.com/protected-data';
//
// (async () => {
//   try {
//     const protectedData = await makeAuthenticatedApiCall(API_URL, 'GET', null, USER_JWT);
//     console.log('Protected data fetched:', protectedData);
//
//     // Example POST request with JWT
//     // const postResult = await makeAuthenticatedApiCall(
//     //   'https://api.example.com/create-item',
//     //   'POST',
//     //   { name: 'New Item', value: 123 },
//     //   USER_JWT
//     // );
//     // console.log('Item created:', postResult);
//   } catch (error) {
//     console.error('Failed to fetch protected data:', error);
//   }
// })();
How it works: This JavaScript snippet demonstrates the standard way to authenticate API requests using a JSON Web Token (JWT). After a user successfully logs in, the server issues a JWT. This token must then be included in the `Authorization` header of subsequent API requests in the format `Bearer YOUR_JWT_TOKEN`. The server can then validate this token to verify the user's identity and grant access to protected resources. This method is widely used for securing client-side applications interacting with RESTful or GraphQL APIs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs