{"id":16304,"library":"bent","title":"Bent HTTP Client","description":"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.","status":"active","version":"7.3.12","language":"javascript","source_language":"en","source_url":"https://github.com/mikeal/bent","tags":["javascript"],"install":[{"cmd":"npm install bent","lang":"bash","label":"npm"},{"cmd":"yarn add bent","lang":"bash","label":"yarn"},{"cmd":"pnpm add bent","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Bent v7 is primarily a CommonJS module for Node.js. While bundlers can handle ESM imports for browser targets, attempting `import bent from 'bent'` in a pure Node.js ESM project will typically result in an error like `ERR_REQUIRE_ESM`.","wrong":"import bent from 'bent'","symbol":"bent","correct":"const bent = require('bent')"},{"note":"When using Bent, you first create a 'bent instance' with desired default options (like response format, method, base URL, accepted status codes) and then call that instance for specific requests.","symbol":"getJSON","correct":"const getJSON = bent('json', 'GET');"},{"note":"For browser applications, Bent is typically bundled, and an ESM import `import bent from 'bent'` is common as bundlers will correctly resolve the browser-specific module entry point. `require` is not standard in browser environments.","wrong":"const bent = require('bent'); // For browser builds","symbol":"bent","correct":"import bent from 'bent'; // When used in browser via a bundler"}],"quickstart":{"code":"const bent = require('bent');\n\nasync function fetchData() {\n  try {\n    // Create a bent instance for GET requests expecting JSON and 200 OK\n    const getJSON = bent('GET', 'json', 200);\n    // Create a bent instance for POST requests expecting 201 Created and JSON input/output\n    const postJSON = bent('POST', 'json', 201);\n\n    console.log('Fetching public JSON data...');\n    const publicData = await getJSON('https://jsonplaceholder.typicode.com/todos/1');\n    console.log('Public Data:', publicData);\n\n    console.log('\\nPosting new data...');\n    const newData = { title: 'foo', body: 'bar', userId: 1 };\n    // Using a fake API endpoint that always returns 201 for POST\n    const postResponse = await postJSON('https://jsonplaceholder.typicode.com/posts', newData);\n    console.log('Post Response:', postResponse);\n\n    // Example of fetching a buffer (e.g., an image, though this is a text file)\n    const getBuffer = bent('GET', 'buffer', 200);\n    console.log('\\nFetching a text file as buffer...');\n    const buffer = await getBuffer('https://jsonplaceholder.typicode.com/todos/1'); // Fetching same data but as buffer\n    console.log('Buffer content start:', buffer.toString().substring(0, 50), '...');\n\n  } catch (error) {\n    console.error('An error occurred:', error.message);\n    if (error.statusCode) {\n      console.error('Status Code:', error.statusCode);\n    }\n    if (error.text) {\n        const errorBody = await error.text();\n        console.error('Error Body:', errorBody);\n    }\n  }\n}\n\nfetchData();\n","lang":"javascript","description":"Demonstrates creating different `bent` instances for GET (JSON) and POST (JSON) requests, and fetching binary data as a buffer, with error handling."},"warnings":[{"fix":"Ensure all expected successful status codes, including `200`, are passed to the `bent` factory function, e.g., `bent(200, 201)`.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Use `const postForm = bent('POST', { 'Content-Type': 'application/x-www-form-urlencoded' }); await postForm(url, new URLSearchParams({ key: 'value' }).toString());`","message":"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`.","severity":"gotcha","affected_versions":">=7.0.0"},{"fix":"Always check the environment and use the appropriate binary type. In Node.js, `Buffer.from('data')`; in browser, `new TextEncoder().encode('data')` for `ArrayBufferView` or `new ArrayBuffer(...)`.","message":"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.","severity":"gotcha","affected_versions":">=7.0.0"},{"fix":"In Node.js ESM projects, if a `bent` ESM build isn't available or preferred, use dynamic `import('bent').then(m => m.default || m)` or consider a CommonJS wrapper. For browser, bundling typically handles ESM imports correctly.","message":"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.","severity":"gotcha","affected_versions":">=7.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change 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.","cause":"Attempting to `import bent from 'bent'` in a Node.js project configured with `\"type\": \"module\"` in `package.json`.","error":"ERR_REQUIRE_ESM"},{"fix":"Modify your `bent` factory call to include all expected successful status codes, e.g., `bent(200, 201, 404)` if 404 is an expected, handled case.","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.","error":"Status code 404 not acceptable"},{"fix":"Ensure 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.","cause":"The `bent` instance was configured with `'json'` as the response format, but the server responded with non-JSON content or an empty body.","error":"Error: Response body is not JSON"},{"fix":"If 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.","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.","error":"Cannot read property 'buffer' of undefined"}],"ecosystem":"npm"}