Back to results for “HTTP & HTTPS Modules”
Node.js › HTTP & HTTPS Modules

How would you make an outgoing HTTP request from Node.js using the built-in fetch API versus the older http.request()?

Advanced

Answer

Modern Node.js (v18+) includes a global fetch() function matching the browser's Fetch API, providing a much more ergonomic, promise-based interface for making HTTP requests without any external dependency -- the older http.request()/https.request() APIs are lower-level, stream-based, and callback-oriented, requiring manually collecting response data chunks; fetch() is now generally the preferred choice for most application code making outgoing requests, with http.request() reserved for cases needing finer-grained control (like streaming a very large response without buffering it).
// Modern: fetch(), built in, promise-based
const response = await fetch('https://api.example.com/users');
const data = await response.json();

// Older: http.request(), lower-level, requires manual chunk collection
const chunks = [];
http.request(url, (res) => {
  res.on('data', (chunk) => chunks.push(chunk));
  res.on('end', () => console.log(Buffer.concat(chunks).toString()));
}).end();
Real-world example A codebase that previously depended on the popular 'node-fetch' or 'axios' packages purely for making simple outgoing API calls removes that dependency entirely after upgrading to Node 18+, switching to the now-built-in global fetch() function with no functional loss for its straightforward use cases.

Common follow-ups: In what specific scenario would you still reach for http.request() directly over fetch(), given fetch()'s simpler API?;How does fetch()'s AbortController-based cancellation compare to how http.request() handles request cancellation?