Got HTTP Retry With Exponential Backoff
Configure the got client to retry transient failures with exponential backoff, status-code allowlists, and per-attempt timeouts for safer polling.
Code
import got from 'got';
const client = got.extend({
retry: {
limit: 4,
methods: ['GET'],
statusCodes: [408, 429, 500, 502, 503, 504],
calculateDelay: ({ computedValue }) => Math.min(computedValue, 8000),
errorCodes: ['ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED'],
},
timeout: { request: 10_000 },
hooks: {
beforeRetry: [
({ attemptCount, url }) => {
console.log('retrying', url.href, 'attempt', attemptCount);
},
],
},
});
const body = await client('https://api.example.com/orders').json();Inside the snippet
Every asynchronous step is awaited, so rejections surface where the call happens.
All steps draw their inputs from the top-level bindings: client, body.
What to watch for
- Dependency check:
got— not built-in, must be present in the project.
Putting it to use
Running the file prints labeled results such as retrying — each operation’s effect is visible in the output.
Core lines
const body = await client('https://api.example.com/orders').json();
({ attemptCount, url }) => {
console.log('retrying', url.href, 'attempt', attemptCount);
},
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- Do I need to install anything before running this?
- Yes: `got` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.