Making Outbound Requests
Global fetch in Node.js
Section titled “Global fetch in Node.js”Since Node.js 18, the fetch API is available globally — no import, no npm install. It is the same Web Fetch API you use in the browser:
// No import needed in Node 18+const response = await fetch('https://api.example.com/data');const data = await response.json();This is a huge improvement over the older http.request approach which required manually assembling chunks from a readable stream.
Fetching JSON from a public API
Section titled “Fetching JSON from a public API”The fetch function returns a Promise that resolves to a Response object. Call .json() on the response to parse the body as JSON — this also returns a Promise, so you await it too.
Needs the Node.js runtime — open in StackBlitz to run.
Error handling with fetch
Section titled “Error handling with fetch”fetch does not throw on non-2xx HTTP status codes. You must check response.ok (a boolean that is true for status codes 200–299) yourself:
Needs the Node.js runtime — open in StackBlitz to run.
A note on http.request
Section titled “A note on http.request”Before fetch, outbound HTTP requests in Node.js used http.request() from the node:http module. It is a lower-level API based on streams. You may encounter it in older codebases:
// Older pattern — collecting chunks manuallyconst http = require('node:http');
http.get('http://example.com', function(res) { let body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { console.log(body); });});For new code, prefer the global fetch — it is cleaner, Promise-based, and isomorphic with browser code.