JAVASCRIPT
Robust API Fetch with Retry and Exponential Backoff
Implement resilient API calls in JavaScript using `fetch` with automatic retry logic and exponential backoff to handle transient network issues and temporary server unavailability.
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
try {
const response = await fetch(url, options);
if (!response.ok) {
if (response.status >= 500 && retries > 0) {
console.warn(`Attempt failed for ${url}. Retrying in ${delay / 1000}s... (${retries} retries left)`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff
}
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
if (retries > 0) {
console.warn(`Fetch failed for ${url}. Retrying in ${delay / 1000}s... (${retries} retries left)`, error);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, options, retries - 1, delay * 2);
}
console.error(`Final fetch attempt failed for ${url}:`, error);
throw error;
}
}
// Example Usage:
// fetchWithRetry('https://api.example.com/data', { method: 'GET' })
// .then(data => console.log('Data fetched:', data))
// .catch(error => console.error('Failed to fetch data after retries:', error));
// Example with POST
// fetchWithRetry('https://api.example.com/items', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ name: 'New Item' })
// })
// .then(data => console.log('Item created:', data))
// .catch(error => console.error('Failed to create item:', error));
How it works: This JavaScript function `fetchWithRetry` enhances standard `fetch` API calls by incorporating automatic retry logic with exponential backoff. If an API request fails due to network issues or server errors (e.g., 5xx status codes), it will reattempt the request after a progressively longer delay, up to a specified number of retries. This makes API integrations more robust and less susceptible to transient failures, improving user experience and application reliability.