Advancedexpress-resforge
Express ResForge
An enterprise-quality engine to standardize API response envelopes, track performance, and format ecosystem errors in Express.
FrameworksFreeMIT
express-resforge
An enterprise-quality, zero-dependency engine designed to standardize API response envelopes, orchestrate asynchronous error pipelines, format third-party library errors, and trace high-precision performance metrics across Express microservices.
Compatible out-of-the-box with Express v4, Express v5, ESM, and CommonJS targets running on Node.js 18+.
šļø Core Architecture Flow
When an HTTP request enters your application,
express-resforge handles the lifecycle safely without causing memory overhead or thread-blocking issues:[Incoming Request]
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā apiKit.requestId() & timer() ā āāāŗ Allocates transaction UUIDs & high-precision tracking
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā apiKit.middleware() ā āāāŗ Dynamically injects semantic shortcuts onto `res`
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā App Business Controllers ā āāāŗ Run workflows through fluent builders (e.g., `res.success()`)
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Plugin Interceptors ā āāāŗ Append global telemetry/metadata on the fly
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā apiKit.errorHandler() ā āāāŗ Catches runtime failures & masks internal stack traces
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā
ā¼
[Outbound Standardized JSON]
š ļø Installation
Install the package via npm:
bashnpm install express-resforge
š Quick Start Guide
1. Initialize Global Middlewares
Mount the
express-resforge middleware core engine at the top of your Express application definition stack:typescriptimport express from class="tok-string">'express'; import { apiKit } from class="tok-string">'express-resforge'; const app = express(); app.use(express.json()); // 1. Mount isolated request lifecycle tracing systems app.use(apiKit.requestId()); app.use(apiKit.requestTimer()); // 2. Initialize global configuration middleware app.use(apiKit.middleware({ apiVersion: class="tok-string">'v1.0.0', errors: { exposeStack: process.env.NODE_ENV === class="tok-string">'development', sanitizeServerErrors: true } }));
2. Implement Standard Route Handlers
Eliminate boilerplate blocks using the native, higher-order asynchronous wrapper
apiKit.async() combined with semantic response triggers:typescript// Traditional clean controller pattern app.get(class="tok-string">'/api/users/:id', apiKit.async(async (req, res) => { const user = await database.find(req.params.id); if (!user) { return res.notFound({ message: class="tok-string">'Target user profile does not exist.' }).send(); } return res.success(user).message(class="tok-string">'Profile loaded successfully.').send(); }));
3. Advanced Fluent Chaining Builder Mechanics
You can cleanly string together custom statuses, business workflow tracking codes, HTTP headers, and secure cookie properties in a single statement:
typescriptapp.post(class="tok-string">'/api/auth/login', apiKit.async(async (req, res) => { const session = await authEngine.authenticate(req.body); return res.created(session) .message(class="tok-string">'Authentication transaction finalized.') .code(class="tok-string">'AUTH_PROCESSED_SUCCESSFULLY') .header(class="tok-string">'X-Auth-Token', session.token) .cookie(class="tok-string">'sid', session.id, { httpOnly: true, secure: true }) .send(); }));
4. Automatic Automated Pagination Calculation
Pass raw list inputs along with pagination parameters.
express-resforge automatically calculates bounding limits, total pages, and boolean indicators:typescriptapp.get(class="tok-string">'/api/products', apiKit.async(async (req, res) => { const products = await database.fetchBatch({ offset: 10, limit: 10 }); // Generates complete totalPages, hasNextPage, and hasPrevPage blocks natively return res.paginate(products, { page: 2, limit: 10, total: 45 }) .message(class="tok-string">'Paginated product inventory batch loaded.') .send(); }));
5. Mount the Catch-All Resilient Error Boundary
Place the global exception boundary tracker at the final exit boundary of your route stack to intercept uncaught failures:
typescript// Always register the error orchestrator after all active operational routes app.use(apiKit.errorHandler());
š Global Plugin System Interceptors
You can hook into the payload formatting engine globally to inject custom tags, regional cloud location traces, or real-time tracking hashes right before the data hits the network stream:
typescriptimport { apiKit } from class="tok-string">'express-resforge'; apiKit.use((payload, req, res) => { // Inject microservice cloud node location tags safely payload.meta.serverCluster = class="tok-string">"aws-us-east-1-prod-node"; return payload; });
š Ecosystem Error Formatters Matrix
Convert diverse validation exceptions from third-party ecosystems into uniform validation shapes. You can parse anomalies explicitly or let the error handler format them automatically:
typescriptimport { apiKit } from class="tok-string">'express-resforge'; app.post(class="tok-string">'/api/register', (req, res) => { const validation = myZodSchema.safeParse(req.body); if (!validation.success) { // Standardizes Zod internal diagnostics into a flat ValidationErrorItem array const cleanErrors = apiKit.formatters.zod(validation.error); return res.unprocessable({ errors: cleanErrors }).send(); } res.created(validation.data).send(); });
Supported out-of-the-box engines include:
apiKit.formatters.zod(error)apiKit.formatters.joi(error)apiKit.formatters.prisma(error)apiKit.formatters.mongoose(error)apiKit.formatters.axios(error)apiKit.formatters.firebase(error)
š Standard Response Schema Envelope
Every payload delivered down the wire matches this production schema model:
Standard Success Response Output
json{ class="tok-string">"success": true, class="tok-string">"statusCode": 200, class="tok-string">"responseCode": class="tok-string">"SUCCESS", class="tok-string">"message": class="tok-string">"Profile loaded successfully.", class="tok-string">"data": { class="tok-string">"profileId": 42 }, class="tok-string">"meta": { class="tok-string">"requestId": class="tok-string">"e30e9d6d-2c81-4b13-be8e-73cb1a4d8d1f", class="tok-string">"timestamp": class="tok-string">"2026-07-13T07:07:00.000Z", class="tok-string">"executionTimeMs": 1.42, class="tok-string">"apiVersion": class="tok-string">"v1.0.0", class="tok-string">"serverCluster": class="tok-string">"aws-us-east-1-prod-node" } }
Standard Paginated Response Output
json{ class="tok-string">"success": true, class="tok-string">"statusCode": 200, class="tok-string">"responseCode": class="tok-string">"SUCCESS", class="tok-string">"message": class="tok-string">"Paginated product inventory batch loaded.", class="tok-string">"data": [{ class="tok-string">"id": 101 }, { class="tok-string">"id": 102 }], class="tok-string">"pagination": { class="tok-string">"page": 2, class="tok-string">"limit": 10, class="tok-string">"totalElements": 45, class="tok-string">"totalPages": 5, class="tok-string">"hasNextPage": true, class="tok-string">"hasPrevPage": true }, class="tok-string">"meta": { class="tok-string">"requestId": class="tok-string">"fa925bc0-80d4-4ce6-a6de-12e09b30c511", class="tok-string">"timestamp": class="tok-string">"2026-07-13T07:07:05.000Z", class="tok-string">"executionTimeMs": 2.10, class="tok-string">"apiVersion": class="tok-string">"v1.0.0" } }
š API Helper Reference Matrix
| Response Helper Method | Status Code | Default Internal System Code |
|---|---|---|
res.success(data, options) | 200 | SUCCESS |
res.created(data, options) | 201 | CREATED |
res.accepted(data, options) | 202 | ACCEPTED |
res.deleted(options) | 200 | DELETED |
res.noContent() | 204 | Empty Body Response |
res.badRequest(options) | 400 | BAD_REQUEST |
res.unauthorized(options) | 401 | UNAUTHORIZED |
res.forbidden(options) | 403 | FORBIDDEN |
res.notFound(options) | 404 | RESOURCE_NOT_FOUND |
res.conflict(options) | 409 | RESOURCE_CONFLICT |
res.unprocessable(options) | 422 | VALIDATION_FAILED |
res.tooManyRequests(options) | 429 | RATE_LIMIT_EXCEEDED |
res.serverError(options) | 500 | INTERNAL_SERVER_ERROR |
š”ļø Security Best Practices Enforced
- Prototype Pollution Immunity: Internal utility methods run isolated loop boundaries that filter out malicious object injection hashes via key hooks like
__proto__orconstructor. - Leak Protection Sanitation: When production settings are active, system level exception dumps (database driver timeouts, runtime faults) are cleanly scrubbed out. The client gets a clear error reference code without revealing system details.
š License
Distributed under the MIT License. See
LICENSE for more information.š„ Maintained By
- Lead Engineer: Vaibhav Dhake
- GitHub Handles: @vaibhavdhake123
For bug reports, feature requests, system discussions, or code contributions, please open an issue tracking card or submit an operational pull request directly on the official source repository tree:
Official Repository: https://github.com/vaibhavdhake123/express-resforge
Built with high precision for microservice telemetry ecosystems.