HTTP Response Object
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.
Common errors
-
Error: Response status code 401 is not 2xx
cause Attempting to call `response.getBody()` on a Response object with a non-2xx (e.g., 4xx or 5xx) HTTP status code.fixImplement a `try...catch` block around `response.getBody()` or explicitly check `response.statusCode` to be within the 200-299 range before calling `getBody()`. -
TypeError: Cannot read properties of undefined (reading 'someHeader')
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.fixAlways 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.
Warnings
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install http-response-object -
yarn add http-response-object -
pnpm add http-response-object
Imports
- Response
import { Response } from 'http-response-object';import Response from 'http-response-object';
- Response (CommonJS)
const { Response } = require('http-response-object');const Response = require('http-response-object'); - Response type
import { Response } from 'http-response-object';import type Response from 'http-response-object';
Quickstart
import Response from 'http-response-object';
// Create a successful response with Buffer body
const successResponse = new Response(
200,
{ 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' },
Buffer.from(JSON.stringify({ message: 'Operation successful!' })),
'https://api.example.com/resource'
);
console.log(`Success Status: ${successResponse.statusCode}`); // 200
console.log(`Content-Type header (auto-lowercased): ${successResponse.headers['content-type']}`); // application/json
console.log(`Body (decoded): ${successResponse.body.toString()}`); // {"message":"Operation successful!"}
try {
// getBody() returns the body for 2xx status codes
const successfulBody = successResponse.getBody().toString();
console.log(`Decoded body via getBody(): ${successfulBody}`);
} catch (e) {
console.error('Unexpected error on successful getBody():', e);
}
// Create an error response with a string body
const errorResponse = new Response(
404,
{ 'X-Trace-ID': 'req-12345' },
'Resource Not Found',
'https://api.example.com/non-existent'
);
console.log(`Error Status: ${errorResponse.statusCode}`); // 404
console.log(`Trace ID header: ${errorResponse.headers['x-trace-id']}`); // req-12345
try {
// getBody() throws an error for non-2xx status codes
errorResponse.getBody();
} catch (e: any) {
console.log(`Caught expected error for 404: ${e.message}`); // Example: 'Response status code 404 is not 2xx'
console.log(`Error object has statusCode property: ${e.statusCode}`); // 404
console.log(`Error object has headers property: ${JSON.stringify(e.headers)}`); // { "x-trace-id": "req-12345" }
console.log(`Error object has url property: ${e.url}`); // https://api.example.com/non-existent
}