Undici Connection Pooling With Custom Agent
Create an undici Agent with per-origin connection limits and pipelining depth, then dispatch pooled HTTP requests with explicit abort timeouts.
Code
import { Agent, fetch } from 'undici';
const agent = new Agent({
connections: 128,
pipelining: 10,
keepAliveTimeout: 60_000,
keepAliveMaxTimeout: 300_000,
});
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
const res = await fetch('https://api.example.com/users', {
dispatcher: agent,
signal: controller.signal,
});
const users = await res.json();
clearTimeout(timer);
agent.close();How the snippet works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Everything borrowed from undici is visible in one line: Agent, fetch.
Everything operates on top-level bindings: agent, controller, timer, res.
Watch out for
- Plan for an install step:
undiciis a real dependency, resolved by the package manager. fetchexist only in browsers — a Node runtime has no shims for them out of the box.
Statements that matter
const res = await fetch('https://api.example.com/users', {
dispatcher: agent,
signal: controller.signal,
});
const timer = setTimeout(() => controller.abort(), 5000);
const controller = new AbortController();
Interactive Tools for This Topic
User-Agent ParserParse a browser User-Agent string into browser, rendering engine, operating system, device type, and bot flag.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `undici`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.