fetch with a timeout and error handling
Abort slow HTTP requests with AbortSignal.timeout and turn non-2xx responses into real errors.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
async function fetchJson(url, { timeoutMs = 8000, signal, ...init } = {}) {
const signals = [AbortSignal.timeout(timeoutMs)];
if (signal) signals.push(signal);
const response = await fetch(url, { ...init, signal: AbortSignal.any(signals) });
if (!response.ok) {
const error = new Error(`HTTP ${response.status} for ${url}`);
error.status = response.status;
throw error;
}
return response.json();
}How it works
fetch has no built-in timeout and only rejects on network failure, not on 404 or 500. This helper adds both: AbortSignal.timeout() cancels the request, and response.ok is checked so callers get an exception with the status code.
A caller-supplied signal is combined with the timeout using AbortSignal.any, so either can cancel the request.
Related snippets
- PHP Tested
Retry a callable with exponential backoff in PHP
Re-run flaky operations with growing delays and jitter, only for chosen exception types.
- TypeScript Tested
Typed fetch helper that checks the response
A fetch wrapper that throws on HTTP errors and validates the JSON body with a type guard.
- JavaScript Tested
Verify a webhook signature in Node.js
Validate an HMAC-SHA256 webhook against the raw request body with a constant-time comparison and replay window.
- PHP Tested
Decode JSON safely in PHP
Parse JSON with exceptions on error and a depth limit, instead of silently getting null.

