Node.js includes fetch (the same API as browsers) for HTTP requests — no package needed in modern versions.
GET
const res = await fetch(url); const data = await res.json();
POST with JSON
Pass method, headers and body: JSON.stringify(data).
Check the status!
fetch only rejects on network failures. A 404 or 500 response still resolves — check res.ok (true for 200–299) or res.status and throw your own error.
Timeouts
fetch(url, { signal: AbortSignal.timeout(5000) }) cancels after 5 seconds, so a slow API cannot hang your server.
Other tips
- Keep API keys in environment variables; send them in headers
- Use
Promise.allfor parallel requests - Retry a few times on temporary errors (429, 503) with a delay
- Cache results that don't change often
Popular alternatives: axios (automatic JSON, interceptors) and undici.
Example
async function api(url, { method = 'GET', body, timeout = 5000 } = {}) {
const res = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.API_TOKEN ?? ''}`,
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(timeout),
});
if (!res.ok) {
throw new Error(`API ${method} ${url} failed with ${res.status}`);
}
return res.status === 204 ? null : res.json();
}
try {
const todo = await api('https://jsonplaceholder.typicode.com/todos/1');
console.log(todo.title);
const created = await api('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: { title: 'Hello', body: 'From Node', userId: 1 },
});
console.log('Created post id:', created.id); // 101
} catch (err) {
console.error(err.name === 'TimeoutError' ? 'API too slow' : err.message);
}
Prints the title of todo 1 and "Created post id: 101" from the free test API. A 404, a 500 or a request taking more than 5 seconds is caught and reported.