Intermediate Node.js Interview QuestionsIntermediatePractical
Node.js · Question 64
How do you make HTTP client requests in Node.js?
Direct answer
Use global fetch (Node 18+) or http.request/https.request for outbound calls — set timeouts with AbortSignal, check response.ok, parse JSON safely, and reuse connection pooling for high-volume service-to-service traffic.
Servers call other APIs constantly — payment webhooks, OAuth token exchange, internal microservices. Node provides fetch aligned with browser semantics plus lower-level http/https modules for streaming or custom TLS.
| API | When to use |
|---|---|
| fetch(url, options) | JSON REST, standard headers, AbortSignal timeout |
| http.request / https.request | Fine-grained streaming, legacy integrations |
| undici (built into fetch) | High-perf HTTP/1.1 client in modern Node |
| Third-party (axios, got) | Interceptors, retries — optional in greenfield Fastify apps |
- AbortSignal.timeout(ms) — cancel hung upstream calls.
- response.ok — fetch does not throw on 404/500; check status explicitly.
- Credentials — server-to-server uses Authorization header, not browser cookies.
http-client.mjs
const API = process.env.API_URL ?? "http://localhost:4000";
async function getTopic(slug) {
const res = await fetch(`${API}/interviews/topics/${slug}`, {
signal: AbortSignal.timeout(5000),
headers: { Accept: "application/json" },
});
if (!res.ok) {
throw new Error(`Upstream ${res.status}: ${slug}`);
}
return res.json();
}
await getTopic("nodejs-interview-questions");