Bent HTTP Client
Bent is a small, functional, and async/await-based HTTP client designed for both Node.js and browsers. Currently stable at version 7.3.12, it provides a fluent API for making HTTP requests with a focus on type-driven configuration. Key differentiators include its remarkably small bundle size (especially for browsers, where it's built on `fetch` with no external dependencies), flexible option parsing (inferring method, format, status codes, and base URL from argument types), and explicit error handling for unacceptable response statuses. While mature, its release cadence is not high, indicating stability over rapid feature churn. It differs from alternatives by prioritizing a functional, curried API over object-oriented design and by requiring explicit declaration of accepted status codes, which helps prevent unexpected success conditions.
Common errors
-
ERR_REQUIRE_ESM
cause Attempting to `import bent from 'bent'` in a Node.js project configured with `"type": "module"` in `package.json`.fixChange the import to `const bent = require('bent');` or use a dynamic import `const bent = await import('bent');` and then access `bent.default || bent` for the actual function. -
Status code 404 not acceptable
cause The HTTP response had a status code (e.g., 404 Not Found) that was not explicitly listed as an acceptable status code when the `bent` instance was created.fixModify your `bent` factory call to include all expected successful status codes, e.g., `bent(200, 201, 404)` if 404 is an expected, handled case. -
Error: Response body is not JSON
cause The `bent` instance was configured with `'json'` as the response format, but the server responded with non-JSON content or an empty body.fixEnsure the server is sending `Content-Type: application/json` and valid JSON. If the content type varies, create `bent` instances that don't specify a response format (`bent()`) and use `response.json()` conditionally, or `bent('string')` for text responses. -
Cannot read property 'buffer' of undefined
cause Trying to use `.buffer()` or `.json()` methods on the raw response object when the `bent` instance was *not* configured for a specific response type, and the method might not exist or be appropriate.fixIf you need a specific format (like `buffer` or `json`), configure your `bent` instance with that format (e.g., `const getBuffer = bent('buffer');`). If not, handle the raw Node.js stream or use the `.arrayBuffer()`/`.text()`/`.json()` methods provided on the response object (matching Fetch API) after checking its type or status.
Warnings
- breaking Bent requires explicit declaration of *all* acceptable status codes. If you provide any status codes, `200` must be explicitly included if you want it to be acceptable. By default, only `200` is acceptable unless overridden.
- gotcha When sending `form-urlencoded` data, Bent does not automatically encode the body or set the `Content-Type` header. You must manually encode the body (e.g., using `URLSearchParams` or `form-urlencoded` package) and set the `Content-Type` header to `application/x-www-form-urlencoded`.
- gotcha Bent uses Node.js `Buffer` for binary data in Node.js environments and `ArrayBuffer` (or `ArrayBufferView` types like `UInt8Array`) in browser environments. Mixing these types or assuming `Buffer` is globally available in browsers will lead to errors.
- gotcha Bent v7 primarily ships as a CommonJS module for Node.js. Direct `import bent from 'bent'` statements in pure Node.js ESM projects will result in `ERR_REQUIRE_ESM` errors unless transpiled or configured via `type: 'module'` with appropriate `require` shims.
Install
-
npm install bent -
yarn add bent -
pnpm add bent
Imports
- bent
import bent from 'bent'
const bent = require('bent') - getJSON
const getJSON = bent('json', 'GET'); - bent
const bent = require('bent'); // For browser buildsimport bent from 'bent'; // When used in browser via a bundler
Quickstart
const bent = require('bent');
async function fetchData() {
try {
// Create a bent instance for GET requests expecting JSON and 200 OK
const getJSON = bent('GET', 'json', 200);
// Create a bent instance for POST requests expecting 201 Created and JSON input/output
const postJSON = bent('POST', 'json', 201);
console.log('Fetching public JSON data...');
const publicData = await getJSON('https://jsonplaceholder.typicode.com/todos/1');
console.log('Public Data:', publicData);
console.log('\nPosting new data...');
const newData = { title: 'foo', body: 'bar', userId: 1 };
// Using a fake API endpoint that always returns 201 for POST
const postResponse = await postJSON('https://jsonplaceholder.typicode.com/posts', newData);
console.log('Post Response:', postResponse);
// Example of fetching a buffer (e.g., an image, though this is a text file)
const getBuffer = bent('GET', 'buffer', 200);
console.log('\nFetching a text file as buffer...');
const buffer = await getBuffer('https://jsonplaceholder.typicode.com/todos/1'); // Fetching same data but as buffer
console.log('Buffer content start:', buffer.toString().substring(0, 50), '...');
} catch (error) {
console.error('An error occurred:', error.message);
if (error.statusCode) {
console.error('Status Code:', error.statusCode);
}
if (error.text) {
const errorBody = await error.text();
console.error('Error Body:', errorBody);
}
}
}
fetchData();