JAVASCRIPT
Authenticating API Requests with Bearer Token
Secure your API calls by implementing Bearer token authentication with JavaScript's `fetch` API, dynamically adding an Authorization header to your requests.
async function authenticatedFetch(url, token, options = {}) {
const headers = {
...options.headers,
'Authorization': `Bearer ${token}`,
};
try {
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Authenticated fetch successful:', data);
return data;
} catch (error) {
console.error('Authenticated fetch error:', error);
return null;
}
}
// Usage example:
// const userToken = 'YOUR_JWT_TOKEN_HERE'; // Get this from login/session
// authenticatedFetch('https://api.example.com/protected-data', userToken)
// .then(data => {
// if (data) {
// console.log('Protected data:', data);
// }
// });
// Example with POST:
// const postData = { item: 'new product' };
// authenticatedFetch('https://api.example.com/products', userToken, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify(postData),
// });
How it works: This snippet demonstrates how to include a Bearer token in your API requests for authentication. It creates a reusable function `authenticatedFetch` that automatically adds an `Authorization` header with the provided token to any `fetch` request, making it easier to interact with protected API endpoints securely across your application.