JAVASCRIPT

Authenticating API Requests with JWT Bearer Token

Learn how to make authenticated API requests by including a JSON Web Token (JWT) in the `Authorization` header as a Bearer token, a common and secure pattern.

async function fetchAuthenticatedData(url, token, options = {}) {
  try {
    const headers = {
      ...options.headers, // Merge any existing headers
      'Authorization': `Bearer ${token}`
    };

    const response = await fetch(url, {
      ...options, // Merge any other fetch options (method, body, etc.)
      headers: headers
    });

    if (response.status === 401 || response.status === 403) {
      // Handle token expiration or invalid token
      console.error("Authentication failed or token expired. Please re-authenticate.");
      // Example: Redirect to login page or refresh token
      // window.location.href = '/login';
      throw new Error(`Authentication error! status: ${response.status}`);
    }

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

    return await response.json();
  } catch (error) {
    console.error("Error in authenticated fetch:", error);
    throw error;
  }
}

// Example usage:
// const userToken = localStorage.getItem('jwtToken'); // Get token from storage
// if (userToken) {
//   fetchAuthenticatedData('https://api.example.com/user/profile', userToken)
//     .then(profileData => console.log('User Profile:', profileData))
//     .catch(error => console.error('Failed to fetch profile:', error));
// } else {
//   console.warn('No authentication token found. Please log in.');
//   // Redirect to login or show login prompt
// }
How it works: This snippet demonstrates how to send an authentication token, specifically a JSON Web Token (JWT), with API requests. The token is included in the `Authorization` header with the `Bearer` scheme, which is a standard practice. The function merges custom headers and gracefully handles 401 (Unauthorized) or 403 (Forbidden) responses, indicating potential authentication issues like an expired or invalid token.

Need help integrating this into your project?

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

Hire DigitalCodeLabs