JAVASCRIPT
Securely Fetch Data from an Authenticated API
Learn to make secure API requests using JavaScript's fetch API, including how to pass authentication tokens and handle common network and HTTP errors effectively.
async function fetchDataWithAuth(url, token) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
// Handle HTTP errors (e.g., 401, 403, 404, 500)
const errorData = await response.json();
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message || response.statusText}`);
}
const data = await response.json();
console.log('API Response:', data);
return data;
} catch (error) {
// Handle network errors (e.g., no internet, DNS issues) or custom errors
console.error('Error fetching data:', error.message);
throw error;
}
}
// Example usage:
// const API_URL = 'https://api.example.com/data';
// const AUTH_TOKEN = 'your_jwt_or_api_key';
// fetchDataWithAuth(API_URL, AUTH_TOKEN)
// .then(data => console.log('Successfully fetched:', data))
// .catch(err => console.error('Failed to fetch:', err.message));
How it works: This snippet demonstrates how to make a secure GET request to an API endpoint using JavaScript's `fetch` API. It includes an `Authorization` header to pass a Bearer token for authentication. The code uses `async/await` for cleaner asynchronous handling and incorporates robust error checking:
1. It checks `response.ok` to catch non-2xx HTTP status codes and parses the error message from the response body.
2. A `try...catch` block handles network-level errors or any exceptions thrown during the process, providing a comprehensive error management strategy for API integrations.