{"id":12949,"library":"centra","title":"Centra HTTP Client","description":"Centra is a lightweight, promise-based HTTP client specifically designed for Node.js environments. It emphasizes a minimal API surface while providing core functionalities like JSON/form body sending, query parameters, custom headers, timeouts, and response streaming. Currently at version 2.7.0, Centra focuses on developer control and efficiency, offering a lean alternative to more feature-rich clients like Axios or Node-fetch. Its primary differentiator is its small footprint and direct interaction with Node's built-in `http` and `https` modules, making it suitable for performance-critical applications or environments where bundle size is a concern. While it provides a fluent API for common tasks, it also allows direct modification of Node's core HTTP request options for advanced use cases. Release cadence appears to be on-demand rather than fixed, with updates driven by feature needs and bug fixes.","status":"active","version":"2.7.0","language":"javascript","source_language":"en","source_url":"https://github.com/ethanent/centra","tags":["javascript","http","https","request","fetch","url","lightweight"],"install":[{"cmd":"npm install centra","lang":"bash","label":"npm"},{"cmd":"yarn add centra","lang":"bash","label":"yarn"},{"cmd":"pnpm add centra","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Centra is a CommonJS-only package. Direct ESM `import` statements are not supported without a transpiler or Node.js's experimental `--experimental-require-module` flag (Node.js 22+).","wrong":"import centra from 'centra'","symbol":"centra","correct":"const centra = require('centra')"},{"note":"The response object returned by `.send()` is a `CentraResponse` instance, providing methods like `.text()`, `.json()`, `.arrayBuffer()`, `.stream()`, and properties like `.statusCode`.","symbol":"CentraResponse","correct":"const centra = require('centra'); /* ... */ const res = await centra('...').send(); // res is a CentraResponse"},{"note":"The `.body()` method is used for sending data in the request body. The second argument specifies the content type ('json' or 'form').","symbol":"body","correct":"centra(url, 'POST').body({ key: 'value' }, 'json').send()"}],"quickstart":{"code":"const centra = require('centra');\nconst fs = require('fs');\nconst path = require('path');\n\n(async () => {\n  try {\n    // Basic GET request and logging text response\n    console.log('Fetching example.com (text response)...');\n    const textRes = await centra('https://example.com').send();\n    console.log('Response status:', textRes.statusCode);\n    // console.log('Response body (truncated):', (await textRes.text()).substring(0, 100) + '...');\n\n    // POST request with JSON body and handling JSON response\n    console.log('\\nSending JSON POST request...');\n    const jsonRes = await centra('https://jsonplaceholder.typicode.com/posts', 'POST')\n      .header('Content-Type', 'application/json')\n      .body({ title: 'foo', body: 'bar', userId: 1 }, 'json')\n      .timeout(5000) // Set a 5-second timeout\n      .send();\n    console.log('JSON POST response status:', jsonRes.statusCode);\n    console.log('JSON POST response body:', await jsonRes.json());\n\n    // Stream a file download\n    console.log('\\nStreaming an image download...');\n    const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png'; // Example PNG\n    const imagePath = path.join(__dirname, 'downloaded_image.png');\n    const imageStream = await centra(imageUrl).send();\n    if (imageStream.statusCode === 200) {\n      imageStream.stream.pipe(fs.createWriteStream(imagePath))\n        .on('finish', () => console.log('Image downloaded to', imagePath))\n        .on('error', (err) => console.error('Stream error:', err));\n    } else {\n      console.error('Failed to download image, status:', imageStream.statusCode);\n    }\n\n  } catch (error) {\n    console.error('An error occurred:', error.message);\n  }\n})();","lang":"javascript","description":"This quickstart demonstrates basic GET and POST requests, sending a JSON body, setting a timeout, and streaming a file download using Centra."},"warnings":[{"fix":"Use `const centra = require('centra')` in CommonJS modules. For ES Modules, consider using a dynamic `import('centra')` or a build step to transpile your code, or ensure your `package.json` does not have `\"type\": \"module\"` if intending to use CJS libraries directly.","message":"Centra is a CommonJS-only package. Attempting to `import centra from 'centra'` in an ES Module context will result in a `TypeError: require is not defined` or `ERR_REQUIRE_ESM` unless specific Node.js flags or transpilation are used.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always chain a `.timeout(milliseconds)` call before `.send()` to prevent requests from hanging. Example: `centra(url).timeout(5000).send()`.","message":"By default, Centra does not apply an automatic timeout to requests. Long-running or stalled requests will hang indefinitely, potentially consuming resources. Users must explicitly configure a timeout using the `.timeout(ms)` method.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"To enable redirect following, use the `.followRedirects(maxRedirects)` method, specifying the maximum number of redirects to follow. Example: `centra(url).followRedirects(5).send()`.","message":"Centra does not automatically follow HTTP redirects by default. If a server responds with a 3xx status code, Centra will resolve the promise with the redirect response itself, rather than initiating a new request to the redirected URL.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Carefully consult Node.js `http.request` documentation before using `.option()`. Always validate the impact of custom options on connection security, certificates, and agent behavior, especially in production environments.","message":"Centra's fluent API allows direct modification of Node's core HTTP request options via `.option(key, value)`. While powerful, incorrectly setting these options can lead to unexpected behavior, connection errors, or security vulnerabilities.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"After `await centra(...).send()`, always check `if (res.statusCode >= 400) { // handle error }`.","message":"Centra will resolve the promise even if the HTTP response status code indicates an error (e.g., 4xx or 5xx). The `res.statusCode` property must be explicitly checked to determine if the request was successful from an application perspective.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Rename your file to `.cjs` or ensure your `package.json` does not have `\"type\": \"module\"` if you intend to use CommonJS. Alternatively, if Node.js 22+ is used, an experimental flag `--experimental-require-module` might allow synchronous `require` of ESM, but `centra` is CJS itself. The most robust fix is to use `const centra = require('centra')` in a CJS context.","cause":"Attempting to use `require()` in a JavaScript file that Node.js treats as an ES module (e.g., a `.mjs` file or a `.js` file in a package with `\"type\": \"module\"` in its `package.json`).","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Ensure you are importing the package as a default function: `const centra = require('centra')`. Centra itself is the function.","cause":"This typically occurs if `require('centra')` is used and then `centra` is called as a property (e.g., `const { centra } = require('centra')`), or if `import` is used for a CommonJS default export. Centra's primary export is a function directly.","error":"TypeError: centra is not a function"},{"fix":"Add a `.timeout(milliseconds)` call to your request chain to ensure requests have a maximum duration. For example, `centra(url).timeout(10000).send()` for a 10-second timeout.","cause":"The HTTP request exceeded a specified duration without receiving a response, or hung indefinitely because no timeout was configured.","error":"Error: Request timed out"},{"fix":"Always wrap your `await centra(...).send()` calls in a `try...catch` block within an `async` function, or chain a `.catch(error => { /* handle error */ })` to the promise.","cause":"The promise returned by `.send()` was rejected (e.g., due to network error, invalid URL, or timeout) and the rejection was not explicitly handled.","error":"UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}