JAVASCRIPT
Integrating Bearer Token Authentication in API Requests
Implement secure API communication by adding a Bearer token to your request headers for authentication in JavaScript web applications using the Fetch API.
async function fetchDataWithBearerToken(url, token) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}` // Add the Bearer token here
}
});
if (!response.ok) {
// Handle specific HTTP status codes, e.g., 401 Unauthorized
if (response.status === 401) {
console.error('Authentication failed. Token might be invalid or expired.');
// Potentially redirect to login or refresh token
}
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log('Data fetched with token:', data);
return data;
} catch (error) {
console.error('Error fetching data with bearer token:', error);
throw error;
}
}
// Example usage:
// const myAuthToken = 'your_secure_jwt_token_here';
// fetchDataWithBearerToken('https://api.example.com/protected-data', myAuthToken)
// .then(data => console.log('Protected data:', data))
// .catch(err => console.error('Failed to get protected data:', err));
How it works: This code snippet demonstrates how to include a Bearer token in the HTTP headers for authenticating API requests. Bearer tokens (often JWTs) are a common way to secure API endpoints. By adding the `Authorization: Bearer <token>` header, the client sends the necessary credential with each request, allowing the server to verify the user's identity and grant access to protected resources. Proper error handling for unauthorized responses (e.g., 401) is also included.