fetch() has no timeout option. If a server hangs, your request hangs with it, and so does the user's spinner. The fix is small: an AbortController and a timer.

The helper

async function fetchWithTimeout(url, { timeout = 3000, ...options } = {}) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeout); try { return await fetch(url, { ...options, signal: controller.signal }); } catch (err) { if (err.name === 'AbortError') { throw new Error(`Request to ${url} timed out after ${timeout} ms`); } throw err; } finally { clearTimeout(timer); } } module.exports = { fetchWithTimeout }; 

What it does:

  1. Creates an AbortController and passes its signal to fetch.
  2. Starts a timer that calls controller.abort() after timeout milliseconds.
  3. Turns the generic AbortError into a message that says what actually happened.
  4. Clears the timer in finally, so a fast response does not leave a timer running.

Use it like a normal fetch:

const res = await fetchWithTimeout('https://example.com/api', { timeout: 5000 }); const data = await res.json(); 

A test you can run

This spins up a local server with a fast and a slow route, so nothing depends on the internet. Save the helper as fetchTimeout.js, then this as test.js:

const http = require('http'); const assert = require('assert'); const { fetchWithTimeout } = require('./fetchTimeout'); const server = http.createServer((req, res) => { const delay = req.url === '/slow' ? 1000 : 0; setTimeout(() => res.end('ok'), delay); }).listen(0, async () => { const base = `http://localhost:${server.address().port}`; const fast = await fetchWithTimeout(`${base}/fast`, { timeout: 500 }); assert.strictEqual(await fast.text(), 'ok'); await assert.rejects( fetchWithTimeout(`${base}/slow`, { timeout: 200 }), /timed out after 200 ms/ ); console.log('all good'); server.closeAllConnections?.(); server.close(); }); 

Run node test.js on Node 18 or newer. It prints all good. I ran it on Node 22.

Notes

  • The timeout covers the time until the response headers arrive. Reading a huge body with res.json() afterwards is not covered. Keep the timer running until you finish reading if that matters to you.
  • Newer runtimes also have AbortSignal.timeout(ms), which does the same thing in one line: fetch(url, { signal: AbortSignal.timeout(3000) }). The helper above is useful when you want a custom error message or need to support older environments.
  • Aborting does not undo work the server already started. For requests that change data, make them safe to retry.

AI-assisted: I used an AI tool to help draft this post. I ran the code myself before publishing.