Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Response formatter

Validated

Return one success, error, and pagination shape across Express, Fastify, and Hono.

The response formatter builds the JSON envelope your API returns. It has a framework-neutral core and thin adapters that send the envelope with the framework's response object.

The block has no root index.ts. Import the core from core, adapters from adapters/, and types from contract.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add response-formatter
import express from "express";
import { ExpressResponse } from "@/blocks/response-formatter/adapters/express";

const app = express();

app.get("/users/:id", (req, res) => {
  return ExpressResponse.success(res, { id: req.params.id }, "User found");
});

Files

response-formatter/
├── adapters/
│   ├── express.ts
│   ├── fastify.ts
│   └── hono.ts
├── contract.ts
└── core.ts

Installation

pnpm dlx blockend-cli add response-formatter

The CLI copies core.ts, contract.ts, and one adapter.

Copy core.ts, contract.ts, and the adapter you need into blocks/response-formatter.

Contract

export interface PaginationParams {
  page: number;
  limit: number;
  total: number;
}

export interface PaginationMeta extends PaginationParams {
  totalPages: number;
  hasNext: boolean;
  hasPrevious: boolean;
}

export interface SuccessResponse<T> {
  success: true;
  data: T;
  message: string;
  requestId?: string;
  meta?: PaginationMeta;
}

export interface ErrorResponse {
  success: false;
  data: null;
  error: {
    message: string;
    details?: unknown;
  };
  requestId?: string;
}

export type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;

Core

import type { ApiResponse, ErrorResponse, PaginationParams } from "./contract";

export class ResponseFormatter {
  static success<T>(data: T, message: string, requestId?: string): ApiResponse<T> {
    return {
      success: true,
      data,
      message,
      ...(requestId ? { requestId } : {})
    };
  }

  static paginated<T>(
    data: T,
    message: string,
    pagination: PaginationParams,
    requestId?: string
  ): ApiResponse<T> {
    const page = Math.max(1, pagination.page);
    const limit = Math.max(1, pagination.limit);
    const total = Math.max(0, pagination.total);
    const totalPages = Math.ceil(total / limit);

    return {
      success: true,
      data,
      message,
      meta: {
        page,
        limit,
        total,
        totalPages,
        hasNext: page < totalPages,
        hasPrevious: page > 1 && totalPages > 0
      },
      ...(requestId ? { requestId } : {})
    };
  }

  static error(error: { message: string; details?: unknown }, requestId?: string): ErrorResponse {
    return {
      success: false,
      data: null,
      error,
      ...(requestId ? { requestId } : {})
    };
  }
}

Express adapter

import type { Response } from "express";

import type { PaginationParams } from "../contract";
import { ResponseFormatter } from "../core";

export class ExpressResponse {
  static success<T>(
    res: Response,
    data: T,
    message = "Request completed successfully",
    statusCode = 200,
    requestId?: string
  ) {
    return res.status(statusCode).json(ResponseFormatter.success(data, message, requestId));
  }

  static paginated<T>(
    res: Response,
    data: T,
    message: string,
    pagination: PaginationParams,
    statusCode = 200,
    requestId?: string
  ) {
    return res
      .status(statusCode)
      .json(ResponseFormatter.paginated(data, message, pagination, requestId));
  }

  static error(
    res: Response,
    statusCode: number,
    message: string,
    details?: unknown,
    requestId?: string
  ) {
    return res.status(statusCode).json(
      ResponseFormatter.error(
        {
          message,
          ...(details ? { details } : {})
        },
        requestId
      )
    );
  }
}

Fastify adapter

import type { FastifyReply } from "fastify";

import type { PaginationParams } from "../contract";
import { ResponseFormatter } from "../core";

export class FastifyResponse {
  static success<T>(
    reply: FastifyReply,
    data: T,
    message = "Request completed successfully",
    statusCode = 200,
    requestId?: string
  ) {
    return reply.status(statusCode).send(ResponseFormatter.success(data, message, requestId));
  }

  static paginated<T>(
    reply: FastifyReply,
    data: T,
    message: string,
    pagination: PaginationParams,
    statusCode = 200,
    requestId?: string
  ) {
    return reply
      .status(statusCode)
      .send(ResponseFormatter.paginated(data, message, pagination, requestId));
  }

  static error(
    reply: FastifyReply,
    statusCode: number,
    message: string,
    details?: unknown,
    requestId?: string
  ) {
    return reply.status(statusCode).send(
      ResponseFormatter.error(
        {
          message,
          ...(details ? { details } : {})
        },
        requestId
      )
    );
  }
}

Hono adapter

import type { Context } from "hono";
import type { ContentfulStatusCode } from "hono/utils/http-status";

import type { PaginationParams } from "../contract";
import { ResponseFormatter } from "../core";

export class HonoResponse {
  static success<T>(
    c: Context,
    data: T,
    message = "Request completed successfully",
    statusCode: ContentfulStatusCode = 200,
    requestId?: string
  ) {
    return c.json(ResponseFormatter.success(data, message, requestId), statusCode);
  }

  static paginated<T>(
    c: Context,
    data: T,
    message: string,
    pagination: PaginationParams,
    statusCode: ContentfulStatusCode = 200,
    requestId?: string
  ) {
    return c.json(ResponseFormatter.paginated(data, message, pagination, requestId), statusCode);
  }

  static error(
    c: Context,
    statusCode: ContentfulStatusCode,
    message: string,
    details?: unknown,
    requestId?: string
  ) {
    return c.json(
      ResponseFormatter.error(
        {
          message,
          ...(details ? { details } : {})
        },
        requestId
      ),
      statusCode
    );
  }
}

Response shapes

Success

{
  "success": true,
  "data": { "id": "usr_123" },
  "message": "User found"
}

Error

{
  "success": false,
  "data": null,
  "error": {
    "message": "User not found"
  }
}

Paginated success

{
  "success": true,
  "data": [],
  "message": "Users fetched",
  "meta": {
    "page": 2,
    "limit": 20,
    "total": 55,
    "totalPages": 3,
    "hasNext": true,
    "hasPrevious": true
  }
}

requestId is added when you pass one. It is omitted otherwise.

Usage

Express

import { ExpressResponse } from "@/blocks/response-formatter/adapters/express";

app.get("/users/:id", (req, res) => {
  return ExpressResponse.success(res, user, "User fetched");
});

app.get("/users", (req, res) => {
  return ExpressResponse.paginated(res, users, "Users fetched", { page: 1, limit: 20, total: 55 });
});

app.get("/missing", (_req, res) => {
  return ExpressResponse.error(res, 404, "User not found");
});

success takes an optional status code before the request ID:

ExpressResponse.success(res, user, "User created", 201, req.get("x-request-id"));

Fastify

import { FastifyResponse } from "@/blocks/response-formatter/adapters/fastify";

app.get("/users/:id", async (request, reply) => {
  return FastifyResponse.success(reply, user, "User fetched");
});

app.get("/users", async (_request, reply) => {
  return FastifyResponse.paginated(reply, users, "Users fetched", {
    page: 1,
    limit: 20,
    total: 55
  });
});

Hono

import { HonoResponse } from "@/blocks/response-formatter/adapters/hono";

app.get("/users/:id", (c) => {
  return HonoResponse.success(c, user, "User fetched");
});

app.get("/users", (c) => {
  return HonoResponse.paginated(c, users, "Users fetched", { page: 1, limit: 20, total: 55 });
});

Core only

Use the core when you need the object without sending it:

import { ResponseFormatter } from "@/blocks/response-formatter/core";

const body = ResponseFormatter.success(user, "User fetched", "req_123");
const errorBody = ResponseFormatter.error(
  { message: "User not found", details: { id: "usr_123" } },
  "req_123"
);
const page = ResponseFormatter.paginated(
  users,
  "Users fetched",
  { page: 1, limit: 20, total: 55 },
  "req_123"
);

Pagination

PaginationParams has three required fields:

interface PaginationParams {
  page: number;
  limit: number;
  total: number;
}

The formatter clamps values below the minimum:

  • page and limit are raised to at least 1.
  • total is raised to at least 0.
  • totalPages is Math.ceil(total / limit).
  • hasNext is true when page < totalPages.
  • hasPrevious is true when page > 1 and totalPages > 0.

It does not fetch data or count rows. Pass the real total from your query.

API reference

ResponseFormatter

class ResponseFormatter {
  static success<T>(data: T, message: string, requestId?: string): ApiResponse<T>;
  static paginated<T>(
    data: T,
    message: string,
    pagination: PaginationParams,
    requestId?: string
  ): ApiResponse<T>;
  static error(error: { message: string; details?: unknown }, requestId?: string): ErrorResponse;
}

ExpressResponse

class ExpressResponse {
  static success<T>(res, data: T, message?: string, statusCode?: number, requestId?: string);
  static paginated<T>(
    res,
    data: T,
    message: string,
    pagination: PaginationParams,
    statusCode?: number,
    requestId?: string
  );
  static error(res, statusCode: number, message: string, details?: unknown, requestId?: string);
}

FastifyResponse

Same methods as ExpressResponse, with FastifyReply instead of Response.

HonoResponse

Same methods as ExpressResponse, with Context and Hono status types instead of Express types.

Types

interface SuccessResponse<T> {
  success: true;
  data: T;
  message: string;
  requestId?: string;
  meta?: PaginationMeta;
}

interface ErrorResponse {
  success: false;
  data: null;
  error: {
    message: string;
    details?: unknown;
  };
  requestId?: string;
}

type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;

Production notes

  • Keep the envelope stable. Clients parse success before reading data or error.
  • The response formatter and the error handler both use success, data, and error. Keep their field names aligned.
  • Do not put internal error details in error.details. The formatter sends whatever you pass.
  • Use one status code convention across routes. success defaults to 200, not 201.
  • Pagination metadata is computed from the values you pass. A wrong total produces wrong hasNext and totalPages.

When not to use it

  • Your framework or API gateway already enforces a response envelope.
  • You serve binary responses, streams, or HTML. The adapters are built for JSON.
  • You need content negotiation across multiple formats.

On this page