Objective HTTP Server
objective-http is a Node.js library that provides Object-Oriented Programming (OOP) proxy classes for constructing HTTP servers. It wraps Node.js's native `http` module, abstracting away low-level stream interactions into a more structured, class-based API. The library emphasizes a clear separation of concerns, allowing developers to define server logic through `Endpoint` classes (for route and request handling) and `Handler` classes (for error handling and request/response stream processing). Currently stable at version 2.1.6, the package appears to have a fairly active release cadence with frequent patch updates. It differentiates itself by offering a highly modular and extensible architecture for building HTTP services, including an `autoconfig` feature for simpler server setups, contrasting with more opinionated frameworks or purely functional approaches.
Common errors
-
TypeError: (0 , server_1.Server) is not a constructor
cause Attempting to import `Server` using an incorrect ESM syntax or path when the package primarily uses CommonJS `require` with nested exports.fixUse the correct CommonJS `require` statement: `const { Server } = require('objective-http').server;` -
Error: Cannot find module 'objective-http/server'
cause This error typically occurs when attempting to use a direct path import for a submodule (`objective-http/server`) in a CommonJS context, or if the package's internal structure doesn't expose modules in that specific way for direct import.fixThe primary entry point for server components is usually `require('objective-http').server`. Avoid direct path imports like `require('objective-http/server')` unless explicitly documented. -
ReferenceError: MyEndpoint is not defined
cause When using `autoconfig` or manually configuring the `Server`, an `Endpoint` class (like `MyEndpoint`) is referenced but not defined or correctly imported within the scope.fixEnsure that any custom `Endpoint` classes are properly defined and instantiated before being passed to the server configuration. For example, `class MyEndpoint { ... }`.
Warnings
- breaking Version 1.3.0 introduced a 'new import signature'. This likely changed how classes and functions were exported, requiring users to update their `require` statements or destructuring paths. Code written for versions prior to 1.3.0 will likely break due to module resolution errors.
- breaking Version 1.4.0 explicitly 'removed json request and response' functionality. If your application relied on `JsonServerRequest` or `JsonServerResponse` classes in versions before 1.4.0, your code would have broken. Note that these classes were later reintroduced in version 2.x, but with potential API changes.
- gotcha The library heavily relies on deeply nested object structures for its classes and utilities, especially when not using `autoconfig`. For example, `EndpointHandler` is under `objective-http.server.handler.endpoint.EndpointHandler`. This can lead to verbose `require` statements and makes direct ESM imports challenging or impossible.
- gotcha The `autoconfig` utility requires an array of `Endpoint` instances and an `env` object. Forgetting to provide these, or providing them in an incorrect format, can lead to server startup failures or requests not being handled correctly.
Install
-
npm install objective-http -
yarn add objective-http -
pnpm add objective-http
Imports
- Server
import { Server } from 'objective-http';const { Server } = require('objective-http').server; - autoconfig
import { autoconfigServer } from 'objective-http/server/autoconfig';const { server: autoconfigServer } = require('objective-http').server.autoconfig; - EndpointHandler, JsonServerRequest, LogErrorHandler
const { handler, request, response } = require('objective-http').server; const { EndpointHandler } = handler.endpoint; const { JsonServerRequest } = request.chunk; const { LogErrorHandler } = handler.error;
Quickstart
const { server: autoconfigServer } = require('objective-http').server.autoconfig;
const { env } = require('node:process');
class MyEndpoint {
route = {
method: 'GET',
path: '/hello'
}
async handle(request) {
console.log(`Received request for: ${request.url}`);
try {
// Simulate some async processing
await new Promise(resolve => setTimeout(resolve, 50));
return {
status: 200,
body: 'Hello, Objective HTTP!'
};
} catch (e) {
console.error('Error handling request:', e);
return {
status: 500,
body: 'Internal server error'
};
}
}
}
// Start the server using autoconfig
autoconfigServer({
env: env,
endpoints: [
new MyEndpoint()
],
options: { port: 3000 } // You can pass http.createServer options here
})
.then(() => console.log('Objective HTTP server listening on port 3000'))
.catch(err => console.error('Failed to start server:', err));
// Optional: Keep the process alive or graceful shutdown
// process.on('SIGINT', () => { console.log('Shutting down...'); process.exit(0); });