Fetching Data: fetch, JSON, Errors and Timeouts
Load data from a server with fetch and async/await, parse JSON, handle HTTP errors, invalid JSON and slow responses with a timeout, and check the same requests independently with curl.
In this lesson you will
- Fetch JSON with async and await
- Handle HTTP errors and bad JSON
- Time out a slow request
- Load several requests in parallel
About 28 minutes
Showing today’s stock without reloading
Ravi keeps the day’s stock in a small data service, and the page should show the numbers without reloading. Browsers provide fetch, which sends an HTTP request and returns a promise. A promise stands for a value that will arrive later, and async and await let you write the waiting as if it were ordinary sequential code. The first await gets the response when its headers arrive, with a status code and a body that is read by a second await, such as response.json().
The most important thing to know about fetch is what it does not do. It does not throw an error when the server answers with a 404 or a 500: the promise resolves, because a response did arrive, and you must check response.ok yourself. It throws only when no response arrives at all, such as when the network is down. Parsing can fail too, when the server sends something that is not JSON. And a request may simply never finish, so give it a timeout with an AbortController. Wrapping all of this in one small function that always returns the same shape of result, success or failure, keeps the rest of the code simple.
| Situation | What fetch does | What you check |
|---|---|---|
| Server answers 200 | Resolves | response.ok is true |
| Server answers 404 or 500 | Resolves | response.ok is false, response.status |
| Network down | Rejects (throws) | catch block |
| Body is not JSON | json() rejects | try/catch around json() |
| No answer in time | Never settles | AbortController timeout |
const http = require('http');
const { exec } = require('child_process');
const sh = cmd => new Promise((ok, no) => exec(cmd, (e, out) => e ? no(e) : ok(out)));
const stock = [{ name: 'Sourdough', left: 12 }, { name: 'Rye', left: 3 }, { name: 'Baguette', left: 0 }];
const server = http.createServer((req, res) => {
if (req.url === '/api/bread') { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(stock)); }
else if (req.url === '/api/broken') { res.setHeader('Content-Type', 'application/json'); res.end('{"name": '); }
else if (req.url === '/api/slow') { setTimeout(() => res.end('[]'), 500); }
else if (req.url === '/api/fail') { res.statusCode = 500; res.end('oops'); }
else { res.statusCode = 404; res.end('not found'); }
});
async function load(url, ms = 200) {
const ctl = new AbortController(); const t = setTimeout(() => ctl.abort(), ms);
try {
const r = await fetch(url, { signal: ctl.signal });
if (!r.ok) return { ok: false, error: 'HTTP ' + r.status };
try { return { ok: true, data: await r.json() }; } catch (e) { return { ok: false, error: 'bad JSON' }; }
} catch (e) { return { ok: false, error: e.name === 'AbortError' ? 'timeout' : 'network: ' + e.name }; }
finally { clearTimeout(t); }
}
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
const names = ['bread', 'missing', 'fail', 'broken', 'slow'];
const results = {};
for (const n of names) results[n] = await load(base + (n === 'missing' ? '/nope' : '/api/' + n));
for (const n of names) console.log(n.padEnd(8), JSON.stringify(results[n]));
const [a, b] = await Promise.all([load(base + '/api/bread'), load(base + '/api/bread')]);
const viaCurl = JSON.parse(await sh('curl -s ' + base + '/api/bread'));
const code500 = await sh('curl -s -o /dev/null -w "%{http_code}" ' + base + '/api/fail');
const code404 = await sh('curl -s -o /dev/null -w "%{http_code}" ' + base + '/nope');
const dead = await load('http://127.0.0.1:1/x');
console.log('parallel results equal:', JSON.stringify(a) === JSON.stringify(b), '| curl agrees:', JSON.stringify(viaCurl) === JSON.stringify(results.bread.data), '| curl codes:', code500, code404, '| closed port:', dead.error);
console.log('DATA ' + JSON.stringify({ results, curl: [code500, code404], eq: JSON.stringify(a) === JSON.stringify(b), dead: dead.error }));
server.closeAllConnections(); server.close();
});
bread {"ok":true,"data":[{"name":"Sourdough","left":12},{"name":"Rye","left":3},{"name":"Baguette","left":0}]}
missing {"ok":false,"error":"HTTP 404"}
fail {"ok":false,"error":"HTTP 500"}
broken {"ok":false,"error":"bad JSON"}
slow {"ok":false,"error":"timeout"}
parallel results equal: true | curl agrees: true | curl codes: 500 404 | closed port: network: TypeError
The script started a real HTTP server on a free local port and called it five times with the same function. The good request returned 3 breads, 15 loaves in all (12 + 3 + 0). The request for a missing URL came back as “HTTP 404” and the failing one as “HTTP 500”: in both cases fetch resolved normally, and only the check of response.ok turned the status into an error. A response whose body was cut off in the middle of a JSON object reported “bad JSON” because json() rejected, and the slow endpoint, which waits half a second against a limit of 200 milliseconds, reported “timeout” after AbortController cancelled it.
The last line shows two more things. Two requests started together with Promise.all finish in parallel and gave equal results (True), which is faster than waiting for one after the other when requests do not depend on each other. A request to a closed port is the “no answer at all” case and was reported as “network: TypeError”: that is the only case in which fetch itself rejects. Because every outcome has the same shape, with ok and either data or error, the code that draws the page needs a single if statement.
Independent check: curl, a separate program that knows nothing about the script, fetched the same endpoint and received identical JSON, and reported the status codes 500 for the failing endpoint and 404 for the missing one, matching what fetch reported. The timeout and invalid JSON cases are behaviours of the client, and the output above, produced by a run, is their evidence.
Check by hand: the three stock values add up to 12 + 3 + 0 = 15. The slow endpoint answers after 500 milliseconds and the limit is 200, so the abort happens first. The broken body, {“name”: , is not valid JSON because the value is missing and the object is not closed.
Always check response.ok or response.status. Many bugs come from code that assumed an error response would throw.
A request is in one of three states: loading, done and failed. Design a visible state for each. A blank area while loading, and a silent failure, look like a broken page to a visitor.
Every program in this lesson was run while the course was written, with Node.js 22, jsdom 31 (a pure-JavaScript DOM used for tests, not a real browser) and Python 3.13. Browsers, tools and their menus change often, so check the official documentation (MDN, the Node.js docs, your provider) for current behaviour. Browsers also enforce cross-origin rules (CORS), which a Node.js script does not, so a request that works here may need a header from the server when made from a web page on a different origin.
Practice
Add a retry that tries a failing request up to three times with a growing delay. Read a header from the response, such as content-type, and print it. Request two endpoints in sequence and in parallel, and compare the time.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does fetch do on a 404 response?
- Resolves, and response.ok is false
- Throws an error
- Retries
- Redirects
Check response.ok.
When does fetch itself reject?
- On any 4xx
- On any 5xx
- Never
- When no response arrives, such as a network failure
Network-level failures.
How do you cancel a slow request?
- clearRequest
- response.stop
- Reload the page
- AbortController
Pass its signal to fetch.
What does Promise.all do?
- Runs them one by one
- Cancels them
- Waits for several promises in parallel
- Retries them
It resolves when all have finished.
Why compare with curl?
- It is faster
- It formats JSON
- It is an independent client
- It is required
The same endpoint, another program.
Summary
- fetch returns a promise; use async and await.
- Check response.ok; only network failures reject.
- Guard against bad JSON and slow responses.
- Return one result shape so the rest of the code stays simple.
Questions
What is CORS?
A browser rule that stops a page from reading responses from another origin unless that server allows it with headers. Servers must send the right headers, so check the documentation of your API.
Should I use fetch or a library?
fetch is enough for most work. Libraries add conveniences such as automatic retries and interceptors. Learn fetch first.
Where do I keep an API key?
Never in front-end code, because every visitor can read it. Keep keys on a server that makes the request for the page.
