JAVASCRIPT
Authenticated API Requests with Bearer Tokens in JavaScript
Securely make API requests with JWT Bearer Token authentication using the Fetch API, demonstrating how to include the Authorization header for authorized access.
async function makeAuthenticatedRequest(url, method = 'GET', body = null, token) {
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
const options = {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
};
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || `HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Authenticated API Request Error:', error);
throw error;
}
}
// Example Usage
// const authToken = 'YOUR_JWT_ACCESS_TOKEN'; // Get this from login/session
// try {
// const userData = await makeAuthenticatedRequest(
// 'https://api.example.com/profile',
// 'GET',
// null,
// authToken
// );
// console.log('User Data:', userData);
// } catch (err) {
// console.error('Failed to fetch profile:', err);
// }
How it works: This function shows how to include a `Bearer` token in the `Authorization` header when making API requests. This is a standard method for authenticating users or clients against protected API endpoints, typically after a user has logged in and received a JSON Web Token (JWT). It also handles request methods, JSON bodies, and basic error checking.