JAVASCRIPT

Authenticating API Requests with Bearer Tokens

Implement API authentication by securely including a Bearer token in the Authorization header of your JavaScript fetch requests, gaining access to protected API endpoints.

async function callAuthenticatedApi(url, token, method = 'GET', data = null) {
  const headers = {
    'Authorization': `Bearer ${token}` // Include the Bearer token
  };

  const fetchOptions = {
    method: method,
    headers: headers
  };

  if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
    headers['Content-Type'] = 'application/json';
    fetchOptions.body = JSON.stringify(data);
  }

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

    if (response.status === 401 || response.status === 403) {
      console.warn('Authentication failed or unauthorized access.');
      // Potentially redirect to login or refresh token
    }

    if (!response.ok) {
      const errorBody = await response.text();
      throw new Error(`API error! Status: ${response.status}, Message: ${errorBody}`);
    }

    const jsonResponse = await response.json();
    return jsonResponse;
  } catch (error) {
    console.error('Authenticated API call failed:', error);
    throw error; // Re-throw for caller handling
  }
}

// Example usage:
// const userToken = 'YOUR_JWT_OR_OAUTH_TOKEN'; // Get this from login/session
// callAuthenticatedApi('https://api.example.com/profile', userToken)
//   .then(profileData => console.log('User Profile:', profileData))
//   .catch(err => console.error('Failed to get profile:', err));

// const newPost = { title: 'Auth Post', content: 'Secured content' };
// callAuthenticatedApi('https://api.example.com/posts', userToken, 'POST', newPost)
//   .then(createdPost => console.log('Post created:', createdPost))
//   .catch(err => console.error('Failed to create post:', err));
How it works: This snippet provides a reusable function for making API requests that require a Bearer token for authentication. It demonstrates how to include the token within the `Authorization` header in the format `Bearer YOUR_TOKEN`. This is a common pattern for securing REST APIs using JWTs (JSON Web Tokens) or OAuth 2.0 access tokens. The function also includes logic for handling different HTTP methods (GET, POST, PUT, PATCH) and properly serializing JSON data for modification requests, along with basic error handling for unauthorized responses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs