A slow upstream API can hold your server's requests open until users give up. Setting a Node.js fetch timeout is the simplest fix, and AbortSignal.timeout() makes it a one-liner. This guide covers the pattern, the error handling most examples skip, and how to combine it with other cancellation signals.
Why fetch has no timeout you can rely on
The Fetch API has no timeout option. If the remote server accepts the connection and then stalls, your await fetch() waits. Node's built-in fetch is powered by undici, which has its own internal timeouts, but they are long and not meant to be your application-level deadline. You should choose a deadline per call, based on what the caller can tolerate.
Node.js fetch timeout with AbortSignal.timeout()
Pass a signal that aborts after a number of milliseconds:
const res = await fetch('https://api.example.com/users', {
signal: AbortSignal.timeout(5000),
});
const data = await res.json();According to MDN, the method is widely available as a Baseline feature. In Node.js it has been available since v17.3, so any supported release has it.
Handle TimeoutError vs AbortError
When the deadline passes, fetch rejects with a DOMException named TimeoutError. A manual abort produces AbortError. Check the name so you can respond differently:
try {
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
return await res.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error('Upstream timed out after 5s');
}
if (err.name === 'AbortError') {
throw err; // cancelled by the caller
}
throw err; // network failure (TypeError) or other
}Note that network failures such as DNS errors surface as a TypeError, so do not treat every TypeError as a timeout.
Cancel on client disconnect with AbortSignal.any()
In an Express handler you often want two reasons to stop: the deadline, or the client leaving. AbortSignal.any() merges signals, and fetch rejects with the reason of whichever fires first.
app.get('/report', async (req, res, next) => {
const controller = new AbortController();
res.on('close', () => {
if (!res.writableFinished) controller.abort();
});
const signal = AbortSignal.any([
AbortSignal.timeout(8000),
controller.signal,
]);
try {
const upstream = await fetch('https://api.example.com/report', { signal });
res.json(await upstream.json());
} catch (err) {
if (err.name === 'TimeoutError') return res.status(504).json({ error: 'Upstream timeout' });
next(err);
}
});Returning 504 for a timeout tells clients and monitoring that the failure was upstream. If you already pass request-scoped data through your app, see AsyncLocalStorage in Node.js for carrying context such as a request ID into your timeout logs.
The timeout also covers reading the body
The signal stays active after headers arrive. If the body streams slowly, res.json() or res.text() rejects with the same TimeoutError. That is usually what you want, because the deadline then describes the whole operation rather than just the first byte. If you need a separate budget for large downloads, use a longer timeout for those calls specifically.
Undici's built-in timeouts
Undici defines headersTimeout and bodyTimeout, which produce errors with codes UND_ERR_HEADERS_TIMEOUT and UND_ERR_BODY_TIMEOUT. Its error documentation recommends matching on error.code rather than instanceof, because the global dispatcher may come from a different undici version. Check the defaults for your Node version, as they have changed over time. In practice, your own AbortSignal.timeout() should be shorter than these, so it fires first and gives you a predictable error.
A reusable fetch wrapper with retries
Wrap the pattern once so every call has a deadline. Retry only idempotent requests, and only on timeouts or 5xx responses:
export async function fetchWithTimeout(url, { timeout = 5000, retries = 2, ...init } = {}) {
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeout) });
if (res.status >= 500 && attempt < retries) continue;
return res;
} catch (err) {
const retryable = err.name === 'TimeoutError';
if (!retryable || attempt >= retries) throw err;
await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));
}
}
}Each attempt gets a fresh signal, so the timeout applies per attempt. Retrying POST requests without an idempotency key can duplicate side effects, so avoid it. To protect your own API from callers that retry aggressively, pair this with rate limiting with Redis.
When to use AbortController with clearTimeout
MDN notes that a timeout signal cannot be cancelled early, and an unreachable signal is not guaranteed to cancel its timer. For most request-sized timeouts this is harmless. If you create very many long-lived timeouts, or need to stop the timer the moment work finishes, use the classic form:
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30000);
try {
await fetch(url, { signal: controller.signal });
} finally {
clearTimeout(timer);
}Be aware that aborting this way produces an AbortError, not a TimeoutError, unless you pass a reason to abort().
Next steps
Add a deadline to every outbound call, return 504 on TimeoutError, and merge signals with AbortSignal.any() when the client can disconnect. Then log timeouts with the upstream host so you can see which dependency is slow. If you are on an older runtime, the Node.js 26 LTS upgrade guide is a good place to plan the move.





