agent-phin Node.js HTTP Client
agent-phin is an ultra-lightweight Node.js HTTP client, forked from the popular phin library, specifically designed to add robust HTTP agent support. It is currently at version 1.0.4 and appears to maintain a release cadence tied to the introduction of specific features, such as the agent support in v1.0.1. Its primary differentiator is its minimal footprint, being significantly smaller than many common HTTP clients like request, axios, or node-fetch, while still providing essential features like POST requests, JSON parsing, and configurable timeouts. The key addition over the original phin is the native capability to utilize custom `http.Agent` or `https.Agent` instances, enabling features like connection pooling (KeepAlive) or proxy integration via libraries like `https-proxy-agent`. It supports both Promise-based and unpromisified (callback-style) API calls, catering to different asynchronous programming preferences in Node.js environments.
Common errors
-
TypeError: await is only valid in async function
cause Attempting to use `await` with `agent-phin`'s Promise-based API outside of an `async` function.fixDeclare the function containing `await` as `async function` or handle the returned Promise using `.then()` and `.catch()`. -
ReferenceError: p is not defined
cause The `agent-phin` module was not correctly imported (e.g., `const p = require('agent-phin')` was omitted or misspelled).fixEnsure you have `const p = require('agent-phin');` at the beginning of your script. -
Error: connect ECONNREFUSED 127.0.0.1:8008
cause The HTTP/HTTPS proxy server specified in the `agent` option (e.g., `http://localhost:8008`) is not running or is unreachable.fixVerify that your proxy server is running and accessible at the specified address and port. Check network connectivity, firewall rules, or proxy configuration.
Warnings
- gotcha All Promise-based API calls (the default behavior) must be used within an `async` function or handled with `.then()`/`.catch()` to properly await the response. Failure to do so will result in unhandled promises or incorrect execution flow.
- gotcha `agent-phin` is a fork of the original `phin` library, specifically adding HTTP agent support. While it aims for compatibility, developers should be aware of its distinct origin and potential divergences from `phin`'s development path, especially concerning features beyond agent support. Always check the `agent-phin` repository for specific updates.
- gotcha When using custom `http.Agent` or `https.Agent` instances, especially for KeepAlive, it's crucial to explicitly call `agent.destroy()` when the agent is no longer needed to prevent resource leaks (e.g., open sockets). `agent-phin` itself does not manage agent lifecycle.
- gotcha The default import style shown in documentation is CommonJS `require()`. While Node.js supports ESM, directly `import`ing `agent-phin` might require specific setup (e.g., `type: "module"` in `package.json` or bundler configuration) and could lead to `ERR_REQUIRE_ESM` if not handled correctly.
Install
-
npm install agent-phin -
yarn add agent-phin -
pnpm add agent-phin
Imports
- phin
import p from 'agent-phin'
const p = require('agent-phin') - unpromisified
import { unpromisified } from 'agent-phin'const p = require('agent-phin').unpromisified - defaults
import { defaults } from 'agent-phin'const ppostjson = require('agent-phin').defaults(...)
Quickstart
const p = require('agent-phin');
const https = require('https');
async function makeRequestWithAgent() {
// Create a KeepAlive agent to reuse TCP connections
const keepAliveAgent = new https.Agent({ keepAlive: true });
try {
const res = await p({
url: 'https://httpbin.org/post',
method: 'POST',
data: {
message: 'Hello from agent-phin with KeepAlive!'
},
agent: keepAliveAgent, // Pass the custom agent here
parse: 'json' // Automatically parse the response body as JSON
});
console.log('Response status:', res.statusCode);
console.log('Response body:', res.body);
} catch (error) {
console.error('Request failed:', error);
} finally {
// It's crucial to destroy the agent when it's no longer needed to prevent resource leaks.
keepAliveAgent.destroy();
}
}
makeRequestWithAgent();