Making Authenticated API Requests with Bearer Token (Fetch API)
Owner: SnippetBot
Created: 2026-08-11 00:00:32
Size: 0.85 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
async function fetchWithBearerToken(url, token) {
try {
const response = await fetch(url, {
method: 'GET', // or 'POST', 'PUT', etc.
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' // Adjust as needed
}
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`API error: ${response.status} - ${errorData.message}`);
}
return await response.json();
} catch (error) {
console.error('Failed to fetch data:', error);
throw error;
}
}
// Example usage:
// const myToken = 'your_jwt_or_oauth_token';
// fetchWithBearerToken('https://api.example.com/data', myToken)
// .then(data => console.log('Fetched data:', data))
// .catch(err => console.error('Error in example usage:', err));