{"id":17700,"library":"http-response-kit","title":"HTTP Response and Error Formatting for Node.js","description":"http-response-kit is a TypeScript-first library designed for standardizing HTTP error and success responses in Node.js applications, particularly useful for RESTful APIs. It provides a comprehensive set of HTTP status codes (1xx-5xx) and convenient factory methods like `HttpError.notFound()` and `HttpResponse.ok()`. Key differentiators include full type safety, zero external dependencies, global and instance-level customization options, and support for both ESM and CommonJS module systems. Currently at version 1.1.0, the package aims for stability and consistency in API response formatting, abstracting away much of the boilerplate associated with handling HTTP statuses and response bodies.","status":"active","version":"1.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/matteo-teodori/http-response-kit","tags":["javascript","http","error","response","api","rest","status-code","express","nodejs","typescript"],"install":[{"cmd":"npm install http-response-kit","lang":"bash","label":"npm"},{"cmd":"yarn add http-response-kit","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-response-kit","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary way to import the HttpError class for creating and throwing HTTP-specific errors.","wrong":"const HttpError = require('http-response-kit').HttpError;","symbol":"HttpError","correct":"import { HttpError } from 'http-response-kit';"},{"note":"Main class for formatting standardized success and error responses.","wrong":"const HttpResponse = require('http-response-kit').HttpResponse;","symbol":"HttpResponse","correct":"import { HttpResponse } from 'http-response-kit';"},{"note":"Used for global configuration of the library, affecting behavior like development mode or timestamp inclusion in responses. Should be called early in your application lifecycle.","wrong":"require('http-response-kit').configure({});","symbol":"configure","correct":"import { configure } from 'http-response-kit';"},{"note":"Recommended factory method for common 4xx client errors like '404 Not Found'. More readable and convenient than direct constructor calls.","wrong":"throw new HttpError(404, { message: 'Resource not found' }); // Less concise","symbol":"HttpError.notFound","correct":"throw HttpError.notFound('Resource not found');"}],"quickstart":{"code":"import express from 'express';\nimport { HttpError, HttpResponse, configure } from 'http-response-kit';\n\nconst app = express();\n\n// Configure the library globally\nconfigure({\n  isDevelopment: process.env.NODE_ENV === 'development',\n  includeTimestamp: true,\n  // Optional: customize default messages or add global metadata\n  defaultErrorMessage: 'An unexpected error occurred.',\n});\n\n// Mock database function\nconst findUser = async (id: string) => {\n  if (id === '123') {\n    return { id: 123, name: 'John Doe', email: 'john.doe@example.com' };\n  }\n  return null;\n};\n\n// Define a route that uses http-response-kit\napp.get('/users/:id', async (req, res) => {\n  try {\n    const user = await findUser(req.params.id);\n    if (!user) {\n      // Throw an HttpError directly\n      throw HttpError.notFound(`User with ID ${req.params.id} not found`);\n    }\n    // Format a success response\n    res.status(200).json(HttpResponse.ok(user, 'User retrieved successfully'));\n  } catch (err) {\n    // Ensure all errors are converted to HttpError for consistent output\n    const error = HttpError.fromError(err);\n    // Send the formatted error response with the correct status code\n    res.status(error.code).json(HttpResponse.error(error));\n  }\n});\n\n// Global error handler middleware for Express\n// This should be defined AFTER all your routes and other middleware.\napp.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {\n  // Convert any unhandled error (including non-HttpErrors) into a standardized HttpError\n  const error = HttpError.fromError(err);\n  // Log the error in development, or less detail in production\n  if (configure().isDevelopment) {\n    console.error('Unhandled API Error:', error.originalError || error);\n  }\n  // Send the standardized error response\n  res.status(error.code).json(HttpResponse.error(error));\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on port ${PORT}`);\n  console.log(`Try: GET http://localhost:${PORT}/users/123`);\n  console.log(`Try: GET http://localhost:${PORT}/users/456`);\n});\n","lang":"typescript","description":"Demonstrates setting up a basic Express server, configuring http-response-kit, handling successful API responses, throwing and catching `HttpError` instances, and implementing a global error handling middleware for consistent API error formatting."},"warnings":[{"fix":"Ensure your Express app includes a final error-handling middleware (`app.use((err, req, res, next) => { ... })`) that calls `HttpError.fromError(err)` before sending the `HttpResponse.error()`.","message":"It is crucial to implement a global error handling middleware (e.g., in Express) that uses `HttpError.fromError(err)` to catch all unhandled exceptions and convert them into standardized `HttpError` instances. Failing to do so can result in inconsistent API responses for unhandled errors, as non-`HttpError` exceptions will not be automatically formatted by the library.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Call `configure()` only once, ideally when your application initializes, to ensure consistent global settings throughout its lifecycle.","message":"The `configure()` function modifies global settings for the library. Calling it multiple times with different configurations might lead to unexpected behavior if not managed carefully. It's best to call `configure()` once at your application's bootstrap phase.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always use named imports (`import { HttpError, HttpResponse } from 'http-response-kit';`) for modern TypeScript/ESM projects. For CJS, use explicit named exports: `const { HttpError } = require('http-response-kit');`.","message":"While `http-response-kit` supports both ESM and CommonJS, developers coming from older Node.js projects might mistakenly use `require()` syntax with default imports or try to directly `new HttpError()` without correctly importing the named exports, leading to runtime errors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure you are using named imports correctly: `import { HttpError } from 'http-response-kit';` for ESM/TypeScript. For CommonJS, use `const { HttpError } = require('http-response-kit');`.","cause":"This typically occurs in a CommonJS environment or incorrect bundling when trying to access `HttpError.notFound` as a property of a default import, or if the library's exports are not correctly interpreted as named exports.","error":"TypeError: (0 , http_response_kit__WEBPACK_IMPORTED_MODULE_0__.HttpError).notFound is not a function"},{"fix":"Add `configure` to your named imports: `import { HttpError, HttpResponse, configure } from 'http-response-kit';`.","cause":"The `configure` function was not imported or is out of scope when called.","error":"ReferenceError: configure is not defined"},{"fix":"Ensure all `async` route handlers and service functions that might throw `HttpError` are wrapped in `try...catch` blocks, or that your global error handling middleware in frameworks like Express correctly intercepts unhandled promise rejections.","cause":"An `HttpError` was thrown in an asynchronous context (e.g., an `async` function) but was not caught by a `try...catch` block, or the global error handler is not properly set up to catch such rejections.","error":"UnhandledPromiseRejectionWarning: HttpError: User not found"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}