Blog

Fix a Node.js fetch timeout that misses the response body

If Node.js logs 200 OK and then hangs at await response.json(), check when your fetch wrapper clears its timeout. fetch() resolves when the status and headers arrive. The body may still be downloading. Give fetch() an AbortSignal.timeout() and keep that signal active while you read the body.

Why fetch returns 200 while response.json() hangs

An AI coding agent can generate this wrapper, pass a mock test, and still leave a request hanging in production. The finally block runs when fetch() settles, so it clears the timer as soon as the headers arrive. A caller awaiting response.json() then has no deadline from this wrapper. MDN’s guide to handling fetch responses.

async function fetchWithTimeout(url, timeoutMs) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    return await fetch(url, { signal: controller.signal });
  } finally {
    clearTimeout(timer);
  }
}

If your wrapper uses Promise.race() with a timer, check for the same boundary. Racing just fetch() also stops waiting at the headers. Even if you race the whole body read, rejecting the timer promise by itself leaves the HTTP request running.

Set a timeout that covers the JSON body

Save this as fetch-json.mjs and run it with Node.js 22 or newer. The helper fetches a URL that should return JSON. The deadline starts before the request and the same signal stays attached through the body read. AbortSignal.any() lets the calling code cancel sooner, for example when its own request is abandoned. Node.js AbortSignal documentation.

export async function fetchJson(url, { timeoutMs = 5_000, signal } = {}) {
  const deadline = AbortSignal.timeout(timeoutMs);
  const requestSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;

  const response = await fetch(url, { signal: requestSignal });
  if (!response.ok) {
    // Release the error response body we won't use.
    await response.body?.cancel().catch(() => {});
    throw new Error(`HTTP ${response.status}`);
  }

  try {
    return await response.json();
  } catch (error) {
    // Preserve the deadline or caller reason if the body read was aborted.
    requestSignal.throwIfAborted();
    throw error;
  }
}

There are two failure points to log during debugging. If fetch() rejects, you never got an HTTP response from that call. If response.json() rejects after a 200, inspect whether the signal fired or the body contained invalid JSON. This helper surfaces TimeoutError when the deadline fires, preserves the caller’s cancellation reason, and lets a JSON SyntaxError propagate. The signal can stop the body download. It cannot interrupt synchronous JSON parsing once it is running.

Test a server that sends headers and stalls

Save this as fetch-json.test.mjs beside the helper. The server binds to a free local port and needs no API key or third-party packages. /stall sends a 200 and starts a JSON object without finishing the response. An immediately resolved json() mock skips this situation entirely. Node.js documentation for flushing response headers.

import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { after, before, test } from 'node:test';
import { fetchJson } from './fetch-json.mjs';

const server = createServer((request, response) => {
  response.setHeader('Content-Type', 'application/json');

  switch (request.url) {
    case '/stall':
      response.flushHeaders();
      response.write('{"ok":');
      return;
    case '/bad-json':
      response.end('{');
      return;
    case '/missing':
      response.statusCode = 404;
      response.end('{"error":"missing"}');
      return;
    default:
      response.end('{"ok":true}');
  }
});

let baseUrl;

before(async () => {
  const listening = once(server, 'listening');
  server.listen(0, '127.0.0.1');
  await listening;
  baseUrl = `http://127.0.0.1:${server.address().port}`;
});

after(async () => {
  const closed = once(server, 'close');
  server.close();
  server.closeAllConnections();
  await closed;
});

test('reads valid JSON and surfaces HTTP and JSON errors', async () => {
  assert.deepEqual(await fetchJson(`${baseUrl}/ok`), { ok: true });
  await assert.rejects(fetchJson(`${baseUrl}/missing`), { message: 'HTTP 404' });
  await assert.rejects(fetchJson(`${baseUrl}/bad-json`), SyntaxError);
});

test('times out after the stalled server sends headers', { timeout: 5_000 }, async () => {
  const nextRequest = once(server, 'request');
  const result = assert.rejects(
    fetchJson(`${baseUrl}/stall`, { timeoutMs: 750 }),
    { name: 'TimeoutError' },
  );

  const [, response] = await nextRequest;
  const disconnected = once(response, 'close');
  assert.equal(response.headersSent, true);
  await result;
  await disconnected;
  assert.equal(response.writableEnded, false);
});

test('preserves caller cancellation', async () => {
  const reason = new Error('Caller left');
  await assert.rejects(
    fetchJson(`${baseUrl}/stall`, { signal: AbortSignal.abort(reason) }),
    (error) => error === reason,
  );
});
node --test fetch-json.test.mjs

The stalled-body test checks that the server sent headers, the helper rejected with TimeoutError, and the connection closed before the server finished the response. To check that it catches your original bug, run it against the old helper before applying the fix. A wrapper that disarms its timer at the headers will hit the test runner’s five-second limit.

Give your coding agent a testable change

Paste this into the agent session alongside the path to your fetch wrapper.

Find where our fetch wrapper starts and clears its timeout. Fix the JSON
request path so a single deadline covers both fetch() and response.json().
Preserve the caller's AbortSignal and the existing HTTP status handling.
Add a local HTTP test that sends 200 headers and partial JSON, leaves the
response open, and checks both timeout rejection and connection closure.
Run the test against the old helper and the fix. Keep retries unchanged.

Use the JSON helper for endpoints that return one complete document. If your app streams model tokens over server-sent events, set a separate policy for waiting for the first event and for idle time between events. A fixed five-second total deadline would cut off a healthy stream that keeps producing tokens past that point.

For more examples of checks that fail when the implementation is broken, see how to test AI-generated code.