Retry-After Header Parser With Clock Skew
Parse Retry-After delay-seconds or HTTP-date values into milliseconds, clamp them to a maximum and correct for server clock skew.
Code
const MAX_DELAY_MS = 24 * 60 * 60 * 1000;
export function parseRetryAfter(value, options = {}) {
if (typeof value !== "string") return null;
const { now = Date.now(), serverDate, maxMs = MAX_DELAY_MS } = options;
if (!Number.isFinite(now)) throw new RangeError("now must be a finite timestamp");
if (!Number.isFinite(maxMs) || maxMs < 0) {
throw new RangeError("maxMs must be a non-negative finite number");
}
if (serverDate !== undefined && !Number.isFinite(serverDate)) {
throw new RangeError("serverDate must be a finite timestamp");
}
const trimmed = value.trim();
if (trimmed === "") return null;
if (/^\d+$/.test(trimmed)) {
const seconds = Number(trimmed);
if (!Number.isSafeInteger(seconds)) return null;
return Math.min(seconds * 1000, maxMs);
}
const target = Date.parse(trimmed);
if (Number.isNaN(target)) return null;
const reference = serverDate === undefined ? now : serverDate;
return Math.min(Math.max(0, target - reference), maxMs);
}How the snippet works
Count the function parseRetryAfter as the entire surface area of Retry-After Header Parser With Clock Skew.
Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.
Caveats
- The guard
typeof value !== "string"short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The main signature reads export function parseRetryAfter(value, options = {})
The surface worth importing is parseRetryAfter; the helpers around it are private to the snippet.
Key statements
if (!Number.isFinite(now)) throw new RangeError("now must be a finite timestamp");
throw new RangeError("maxMs must be a non-negative finite number");
throw new RangeError("serverDate must be a finite timestamp");
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.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Does the code validate its input?
- `RangeError` is raised at the guard (`typeof value !== "string"`), so invalid state never reaches the main logic.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `parseRetryAfter` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.