Undici is the HTTP/1.1 client that powers Node.js's built-in fetch. It is significantly faster than the legacy http module and provides connection pooling, interceptors, and streaming.
Installation
npm install undici
Note: Undici is bundled with Node.js 18+ as the engine behind globalThis.fetch.
Basic Requests
import { request } from "undici";
// Simple GET
const { statusCode, headers, body } = await request("https://api.github.com/users/nodejs", {
headers: { "User-Agent": "undici-example" }
});
const data = await body.json();
console.log(`${data.login}: ${data.public_repos} repos`);
Connection Pooling
import { Pool } from "undici";
// Create a pool with 10 connections
const pool = new Pool("https://api.example.com", {
connections: 10,
pipelining: 1
});
// Make concurrent requests through the pool
const results = await Promise.all(
Array.from({ length: 100 }, (_, i) =>
pool.request({ path: `/items/${i}`, method: "GET" })
.then(({ body }) => body.json())
)
);
console.log(`Fetched ${results.length} items`);
await pool.close();
Interceptors
import { Agent, setGlobalDispatcher } from "undici";
const agent = new Agent().compose([
(dispatch) => (opts, handler) => {
opts.headers = {
...opts.headers,
"Authorization": "Bearer my-token"
};
return dispatch(opts, handler);
}
]);
setGlobalDispatcher(agent);
// All requests now include the auth header
const { body } = await request("https://api.example.com/me");
Streaming Downloads
import { stream } from "undici";
import { createWriteStream } from "node:fs";
await stream("https://example.com/large-file.zip", { method: "GET" }, () => {
return createWriteStream("output.zip");
});
MockAgent for Testing
import { MockAgent, setGlobalDispatcher } from "undici";
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
const mockPool = mockAgent.get("https://api.example.com");
mockPool.intercept({ path: "/users/1", method: "GET" }).reply(200, {
id: 1, name: "Test User"
});
// This now returns the mocked response
const { body } = await request("https://api.example.com/users/1");
console.log(await body.json()); // { id: 1, name: "Test User" }
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)