npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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.

Readme

BaR — TypeScript API response builder for Express and Fastify

npm version CI License: MIT TypeScript

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

  • 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.builder over ad-hoc res.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-js

Install 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)
        → HTTP

Features

  • Zero runtime dependencies — Express, Fastify, and @fastify/cookie are 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-level message.
  • Pagination: .paginate(data, { strategy: 'offset' | 'cursor', ... }).
  • Validation: .as.validationError(errors) and normalizeValidationErrors().
  • Adapters: @vorlaxen-labs/bar-js/adapters/express and /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"); // 404

Errors

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 |

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.