{"id":16073,"library":"http-response-object","title":"HTTP Response Object","description":"http-response-object is a minimalistic JavaScript library designed to encapsulate HTTP response data into a simple, consistent object. It provides a standardized structure for common response properties such as `statusCode`, `headers`, `body`, and `url`, which simplifies handling and passing HTTP responses across different application layers. The current stable version is 3.0.2. While the project maintains a focused scope, it receives updates to ensure compatibility and address specific use cases. Key differentiators include its lightweight design, explicit support for both Node.js `Buffer` and `String` for the response body, and the inclusion of TypeScript types, which enhance developer experience through strong type checking. It is frequently employed in contexts requiring a normalized representation of HTTP responses, such as in HTTP client abstractions, proxy implementations, or server-side rendering logic, offering a predictable interface for response data.","status":"active","version":"3.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/ForbesLindesay/http-response-object","tags":["javascript","http","https","response","request","typescript"],"install":[{"cmd":"npm install http-response-object","lang":"bash","label":"npm"},{"cmd":"yarn add http-response-object","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-response-object","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary export is a default class, as commonly used for single-purpose libraries.","wrong":"import { Response } from 'http-response-object';","symbol":"Response","correct":"import Response from 'http-response-object';"},{"note":"As shown in the official documentation, the module exports the Response class directly.","wrong":"const { Response } = require('http-response-object');","symbol":"Response (CommonJS)","correct":"const Response = require('http-response-object');"},{"note":"When only importing the type for TypeScript, use the default import syntax with 'type'.","wrong":"import { Response } from 'http-response-object';","symbol":"Response type","correct":"import type Response from 'http-response-object';"}],"quickstart":{"code":"import Response from 'http-response-object';\n\n// Create a successful response with Buffer body\nconst successResponse = new Response(\n  200,\n  { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' },\n  Buffer.from(JSON.stringify({ message: 'Operation successful!' })),\n  'https://api.example.com/resource'\n);\n\nconsole.log(`Success Status: ${successResponse.statusCode}`); // 200\nconsole.log(`Content-Type header (auto-lowercased): ${successResponse.headers['content-type']}`); // application/json\nconsole.log(`Body (decoded): ${successResponse.body.toString()}`); // {\"message\":\"Operation successful!\"}\n\ntry {\n  // getBody() returns the body for 2xx status codes\n  const successfulBody = successResponse.getBody().toString();\n  console.log(`Decoded body via getBody(): ${successfulBody}`);\n} catch (e) {\n  console.error('Unexpected error on successful getBody():', e);\n}\n\n// Create an error response with a string body\nconst errorResponse = new Response(\n  404,\n  { 'X-Trace-ID': 'req-12345' },\n  'Resource Not Found',\n  'https://api.example.com/non-existent'\n);\n\nconsole.log(`Error Status: ${errorResponse.statusCode}`); // 404\nconsole.log(`Trace ID header: ${errorResponse.headers['x-trace-id']}`); // req-12345\n\ntry {\n  // getBody() throws an error for non-2xx status codes\n  errorResponse.getBody();\n} catch (e: any) {\n  console.log(`Caught expected error for 404: ${e.message}`); // Example: 'Response status code 404 is not 2xx'\n  console.log(`Error object has statusCode property: ${e.statusCode}`); // 404\n  console.log(`Error object has headers property: ${JSON.stringify(e.headers)}`); // { \"x-trace-id\": \"req-12345\" }\n  console.log(`Error object has url property: ${e.url}`); // https://api.example.com/non-existent\n}","lang":"typescript","description":"This quickstart demonstrates how to create `Response` objects for both successful and error scenarios, access their properties, and utilize the `getBody()` method, including handling its error-throwing behavior for non-2xx status codes. It also highlights the automatic lowercasing of header keys."},"warnings":[{"fix":"Always access headers using their lowercase form (e.g., `response.headers['content-type']`) or normalize keys before comparison.","message":"The `headers` object keys are automatically converted to lowercase upon instantiation. If you rely on case-sensitive header names, this will lead to unexpected behavior.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always wrap calls to `getBody()` in a `try...catch` block or ensure `statusCode` is 2xx before calling it. The thrown error object will contain `statusCode`, `headers`, `body`, and `url` properties for inspection.","message":"The `getBody()` method will throw an error if the `statusCode` of the response is not in the 2xx range. This is designed to enforce checking for successful HTTP responses before attempting to process the body.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If expecting a string, call `.toString()` on `response.body`. If expecting a Buffer, ensure inputs are always Buffers or convert strings to Buffers explicitly.","message":"The `body` property can be either a `Buffer` (typical for Node.js server-side) or a `String` (potentially for lighter-weight clients). Be consistent in your application's handling or always convert to your desired type.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Implement a `try...catch` block around `response.getBody()` or explicitly check `response.statusCode` to be within the 200-299 range before calling `getBody()`.","cause":"Attempting to call `response.getBody()` on a Response object with a non-2xx (e.g., 4xx or 5xx) HTTP status code.","error":"Error: Response status code 401 is not 2xx"},{"fix":"Always access headers using their lowercase names (e.g., `response.headers['content-type']` instead of `response.headers['Content-Type']`). Verify the header exists before accessing if it's optional.","cause":"Attempting to access a header with an incorrect or case-sensitive key, or a header that does not exist. `http-response-object` automatically lowercases all header keys.","error":"TypeError: Cannot read properties of undefined (reading 'someHeader')"}],"ecosystem":"npm"}