@vorlaxen-labs/bar-js
v1.0.0
Published
TypeScript API response builder for Express and Fastify — fluent chaining, consistent JSON schema, request IDs, and optional security headers.
Maintainers
Readme
BaR — TypeScript API response builder for Express and Fastify
BaR (Build a Response) is a framework-agnostic TypeScript library for Node.js APIs. It gives you a fluent ResponseBuilder, a consistent JSON response envelope, and optional adapters for Express and Fastify. You chain status, message, data, headers, and cookies, then call .build() once. An adapter attaches the builder to your framework; a dispatcher sends the finished response over HTTP.
Table of contents
- When to use BaR
- Installation
- Quick start
- Features
- Standard response envelope
- Package exports
- Usage
- Documentation
- For maintainers
- License
When to use BaR
- You want every REST endpoint to return the same JSON shape (
success,data,message,metadata). - You need request IDs and timestamps in responses for logging and support.
- You use Express or Fastify and prefer
res.builder/reply.builderover ad-hocres.json(). - You may switch frameworks later: the core builder and dispatcher pattern stay the same.
- You care about zero runtime dependencies in the published package; framework libraries are optional peers in your app.
Installation
npm install @vorlaxen-labs/bar-jsInstall peers only for the adapters you use:
| Adapter | In your app |
| ------- | ------------------------------------- |
| Express | npm install express |
| Fastify | npm install fastify @fastify/cookie |
Details: docs/adapters.md.
Quick start
Express adapter
import express, { Request, Response } from "express";
import "@vorlaxen-labs/bar-js/adapters/express"; // side-effect: types for req.bar / res.builder
import { BarExpressAdapter } from "@vorlaxen-labs/bar-js/adapters/express";
const app = express();
app.use(express.json());
app.use(
new BarExpressAdapter({
withDefaultHeaders: true,
logger: console,
}).handler(),
);
app.get("/api/test", (_req: Request, res: Response) => {
return res.builder.as.ok({ hello: "world" }, "Operation successful").build();
});The adapter import is a TypeScript side effect: it loads the Express augmentation so res.builder and req.bar.ctx (including req.bar.ctx.request_id) are typed. The Fastify subpath does the same for reply.builder and request.bar.
Fastify plugin
Register @fastify/cookie before BaR so cookie dispatch works.
import Fastify from "fastify";
import cookie from "@fastify/cookie";
import "@vorlaxen-labs/bar-js/adapters/fastify"; // side-effect: types for request.bar / reply.builder
import { registerBarFastify } from "@vorlaxen-labs/bar-js/adapters/fastify";
const app = Fastify();
await app.register(cookie);
registerBarFastify(app, { withDefaultHeaders: true, logger: console });
app.get("/api/test", async (_request, reply) => {
reply.builder.as.ok({ hello: "world" }).build();
return reply;
});.build() is synchronous and returns BaRFinalResult — not reply and not a Promise. The Fastify dispatcher already calls reply.send() inside .build(). In an async handler, return reply afterward so Fastify does not treat that result object as a second payload.
After .build()
The adapter runs before your route (it attaches context and the builder). .build() then hands the envelope to the dispatcher, which writes HTTP:
request → adapter middleware (ctx + builder)
→ your route
→ res.builder / reply.builder … .build()
→ dispatcher (status, headers, cookies, JSON)
→ HTTPFeatures
- Zero runtime dependencies — Express, Fastify, and
@fastify/cookieare optional peers. - Fluent API — Chain
.status(),.data(),.message(), headers, cookies, then.build(). - Semantic presets —
.as.ok(),.as.created(),.as.notFound(), and more instead of raw status codes. - Adapters and dispatchers — One
.build()assembles the body; the dispatcher sets status, headers, and JSON. - Traceability —
request_id, ISO timestamps, and optional incoming correlation headers. - Security defaults — Optional security and cache headers via adapter options.
- TypeScript-first — Strict types and framework augmentations when you import adapter subpaths.
Standard response envelope
Every built response follows this shape (frontend-friendly and predictable):
{
"success": true,
"timestamp": "2026-05-04T13:52:00.000Z",
"message": "Operation successful",
"data": {
"hello": "world"
},
"metadata": {
"status_code": 200,
"request_id": "fddc7272-4405-4001-9858-ab40007bfa11",
"server_time": "2026-05-04T13:52:00.000Z"
}
}Error responses use a structured error object (no top-level message):
{
"success": false,
"timestamp": "2026-05-04T13:52:00.000Z",
"data": null,
"error": {
"code": "BAD_REQUEST",
"message": "email is required"
},
"metadata": {
"status_code": 400,
"request_id": "fddc7272-4405-4001-9858-ab40007bfa11",
"server_time": "2026-05-04T13:52:00.000Z"
}
}Full schema: docs/api-reference.md.
Package exports
| Import | Purpose |
| ---------------------------------------- | ------------------------------------------------------------------ |
| @vorlaxen-labs/bar-js | Core: ResponseBuilder, BaR, hooks, constants, IBaRDispatcher |
| @vorlaxen-labs/bar-js/adapters/express | BarExpressAdapter, Express type augmentation |
| @vorlaxen-labs/bar-js/adapters/fastify | registerBarFastify, Fastify type augmentation |
Highlights
- Failures expose
error: { code, message, details? }instead of a top-levelmessage. - Pagination:
.paginate(data, { strategy: 'offset' | 'cursor', ... }). - Validation:
.as.validationError(errors)andnormalizeValidationErrors(). - Adapters:
@vorlaxen-labs/bar-js/adapters/expressand/adapters/fastify.
Usage
Semantic presets (.as)
res.builder.as.ok(data, "Success"); // 200
res.builder.as.created(newItem); // 201
res.builder.as.badRequest("email is required"); // 400
res.builder.as.unauthorized("Access denied"); // 401
res.builder.as.notFound("User not found"); // 404Errors
app.post("/api/users", (req: Request, res: Response) => {
if (!req.body?.email) {
return res.builder.as.badRequest("email is required").build();
}
try {
const user = { id: "u_1", email: req.body.email };
return res.builder.as.created(user, "User created").build();
} catch {
return res.builder.as.internalServerError().build();
}
});For rejected promises, await res.builder.wrap(promise) then .build() — see advanced chaining.
Advanced chaining
return res.builder
.status(202)
.data({ taskId: "abc-123" })
.message("Task queued successfully")
.header("X-Custom-Header", "BaR")
.setMeta({ cluster: "us-east-1" })
.build();More examples: docs/advanced-chaining.md.
Documentation
Guides live in docs/:
| Guide | Description |
| ---------------------------------------------- | -------------------------------------------------- |
| Getting started | Install, exports, migration, first routes |
| Adapters | Express, Fastify, vanilla Node, custom dispatchers |
| Advanced chaining | Headers, cookies, wrap(), hooks, pagination |
| API reference | Presets, builder methods, response schema |
- npm:
@vorlaxen-labs/bar-js - Repository: github.com/vorlaxen-labs/bar-js
For maintainers
Automated npm publish from main is described in docs/PUBLISHING.md (GitHub NPM_TOKEN secret; no .env required in CI).
License
Distributed under the MIT License. See LICENSE for details.
