Fetch and AbortSignal
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Distinguish status from rejection
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});await withServer((q,r)=>{r.statusCode=404;r.setHeader('content-type','application/json');r.end('{"error":"missing"}');},async base=>{const r=await localFetch(base);console.log(r.ok,r.status,(await r.json()).error);});Run:
node main.mjsExpected stdout:
false 404 missingExit status: 0. Expected stderr: empty.
How it works
A fulfilled fetch does not imply a successful status: check response.ok or response.status and consume or cancel the body. Network failures and aborts reject the promise; JSON parsing can also reject separately. Node fetch uses Undici internally and does not provide the browser’s origin-based CORS enforcement. The first fixture shows a 404 response with JSON. The second starts a response but deliberately withholds completion until a client deadline; it uses a finite local server, not an external network. The exact wall-clock duration is not a guarantee.
Cancel a pending local request
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});await withServer((q,r)=>{/* intentionally wait; fixture closes connection */},async base=>{try{await localFetch(base,{signal:AbortSignal.timeout(100)});}catch(e){console.log(e.name);}});Run:
node main.mjsExpected stdout:
TimeoutErrorExit status: 0. Expected stderr: empty.
Common mistake
Do not blindly call response.json() for every response: a server may return HTML or malformed JSON. Do not retry every failure or allow arbitrary untrusted destinations and redirects.
Practice
Modify the first handler to return plain text and decide how a client should recognize the media type before parsing.
Further reading: Authoritative source 1 · Authoritative source 2. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fetch and AbortSignal — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
How does fetch normally treat an HTTP 404?
What cancels a request when a deadline expires?
Does Node fetch enforce browser CORS as a security boundary?