Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Health check

Validated

Run dependency checks with per-check timeouts and return a JSON health report.

The health check block runs a list of checks, waits for all of them, and turns the results into one JSON report. A failed critical check makes the report unhealthy. A failed non-critical check makes it degraded.

The block has no root index.ts. Import createHealth from core/create-health and the framework helpers from adapters/.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add health-check
import express from "express";
import { createHealth } from "@/blocks/health-check/core/create-health";
import { registerExpressHealthRoute } from "@/blocks/health-check/adapters/express";

const app = express();

const health = createHealth({
  checks: [
    {
      name: "database",
      critical: true,
      timeoutMs: 5_000,
      async run() {
        await db.query("SELECT 1");
      }
    }
  ]
});

registerExpressHealthRoute(app, health); // GET /health

registerExpressHealthRoute returns 200 for healthy and degraded, and 503 for unhealthy. It does not add liveness or readiness endpoints. The production guide shows how to build those on top of health.run().

Files

health-check/
├── adapters/
│   ├── express.ts
│   ├── fastify.ts
│   └── hono.ts
├── core/
│   ├── build-report.ts
│   ├── calculate-status.ts
│   ├── create-health.ts
│   ├── run-check.ts
│   ├── run-checks.ts
│   └── validate-config.ts
└── types/
    └── index.ts

CLI installs the base files, the types/ folder, and one adapter. There is no barrel file. Import each module by its path.

Installation

pnpm dlx blockend-cli add health-check

Detect project

Blockend reads blockend.json and picks the adapter for your framework.

Copy files

The core, types, selected adapter, and tests are written to your blocks directory.

Copy the files into blocks/health-check. The core has no runtime dependencies. Install your framework package for the adapter you use.

Types

// health status of the entire system
export type HealthStatus = "healthy" | "degraded" | "unhealthy";

// status of an individual check
export type CheckStatus = "healthy" | "unhealthy";

export interface HealthCheck {
  /** Unique name of the check. Example: "database", "redis" */
  name: string;

  /** Whether failure should make the application unhealthy. */
  critical: boolean;

  /** Optional human-friendly message shown when the check fails. */
  message?: string;

  /** Timeout for this specific check in milliseconds. Prevents hanging. */
  timeoutMs?: number;

  /** Actual health check implementation. Throw an error if it fails. */
  run(): Promise<void>;
}

export interface HealthCheckResult {
  name: string;
  critical: boolean;
  status: CheckStatus;
  duration: number; // in milliseconds
  message?: string;
  error?: string; // Sanitized to string to prevent leaking stack traces
}

export interface HealthReport {
  status: HealthStatus;
  timestamp: string;
  uptime: number; // in seconds
  checks: HealthCheckResult[];
}

// Extension points: Allow teams to override default policies
export type StatusCalculator = (results: HealthCheckResult[]) => HealthStatus;
export type ReportBuilder = (results: HealthCheckResult[], status: HealthStatus) => HealthReport;

export interface CreateHealthOptions {
  checks: HealthCheck[];
  /** Global fallback timeout in milliseconds (default: 5000) */
  defaultTimeoutMs?: number;
  /** Optional custom status calculation logic */
  calculateStatus?: StatusCalculator;
  /** Optional custom report generation logic */
  buildReport?: ReportBuilder;
}

export interface Health {
  run(): Promise<HealthReport>;
}

Config validation

import type { CreateHealthOptions } from "../types/index";

export function validateConfig(options: CreateHealthOptions): void {
  if (!options.checks || !Array.isArray(options.checks)) {
    throw new Error("Health configuration error: 'checks' must be a valid array.");
  }

  if (options.checks.length === 0) {
    throw new Error("Health configuration error: 'checks' array cannot be empty.");
  }

  const names = new Set<string>();

  for (const check of options.checks) {
    if (!check.name || typeof check.name !== "string" || check.name.trim() === "") {
      throw new Error(
        "Health configuration error: Each check must have a non-empty string 'name'."
      );
    }

    if (names.has(check.name)) {
      throw new Error(
        `Health configuration error: Duplicate check name found: "${check.name}". Names must be unique.`
      );
    }
    names.add(check.name);

    if (typeof check.run !== "function") {
      throw new Error(
        `Health configuration error: Check "${check.name}" is missing a valid 'run' function.`
      );
    }

    if (
      check.timeoutMs !== undefined &&
      (typeof check.timeoutMs !== "number" || check.timeoutMs <= 0)
    ) {
      throw new Error(
        `Health configuration error: Check "${check.name}" has an invalid 'timeoutMs'. It must be a positive number.`
      );
    }
  }

  if (
    options.defaultTimeoutMs !== undefined &&
    (typeof options.defaultTimeoutMs !== "number" || options.defaultTimeoutMs <= 0)
  ) {
    throw new Error("Health configuration error: 'defaultTimeoutMs' must be a positive number.");
  }
}

Single check runner

import type { HealthCheck, HealthCheckResult } from "../types/index";

export async function runCheck(
  check: HealthCheck,
  defaultTimeoutMs = 5000
): Promise<HealthCheckResult> {
  const start = performance.now();
  const timeout = check.timeoutMs ?? defaultTimeoutMs;

  try {
    // Enforce timeout to prevent a single slow dependency from hanging the entire health request
    const timeoutPromise = new Promise<never>((_, reject) => {
      setTimeout(() => reject(new Error(`Check timed out after ${timeout}ms`)), timeout);
    });

    await Promise.race([check.run(), timeoutPromise]);

    return {
      name: check.name,
      critical: check.critical,
      status: "healthy",
      duration: performance.now() - start,
      ...(check.message === undefined ? {} : { message: check.message })
    };
  } catch (error) {
    const duration = performance.now() - start;

    // Sanitize error: never expose raw Error objects (stack traces) in production APIs
    const errorMessage = error instanceof Error ? error.message : String(error);

    return {
      name: check.name,
      critical: check.critical,
      status: "unhealthy",
      duration,
      ...(check.message === undefined ? {} : { message: check.message }),
      error: errorMessage
    };
  }
}

Concurrent runner

import type { HealthCheck, HealthCheckResult } from "../types/index";
import { runCheck } from "./run-check";

export async function runChecks(
  checks: HealthCheck[],
  defaultTimeoutMs?: number
): Promise<HealthCheckResult[]> {
  const tasks = checks.map((check) => runCheck(check, defaultTimeoutMs));
  return await Promise.all(tasks);
}

Status calculation

import type { HealthCheckResult, HealthStatus } from "../types/index";

export function calculateStatus(results: HealthCheckResult[]): HealthStatus {
  const hasCriticalFailure = results.some(
    (result) => result.critical && result.status === "unhealthy"
  );

  if (hasCriticalFailure) {
    return "unhealthy";
  }

  const hasOptionalFailure = results.some(
    (result) => !result.critical && result.status === "unhealthy"
  );

  if (hasOptionalFailure) {
    return "degraded";
  }

  return "healthy";
}

Report builder

import type { HealthCheckResult, HealthReport, HealthStatus } from "../types/index";

export function buildReport(results: HealthCheckResult[], status: HealthStatus): HealthReport {
  // Safely get uptime for Node.js, fallback to 0 for other environments
  const uptime =
    typeof process !== "undefined" && typeof process.uptime === "function" ? process.uptime() : 0;

  return {
    status,
    checks: results,
    timestamp: new Date().toISOString(),
    uptime
  };
}

Factory

import type { CreateHealthOptions, Health } from "../types/index";
import { buildReport as defaultBuildReport } from "./build-report";
import { calculateStatus as defaultCalculateStatus } from "./calculate-status";
import { runChecks } from "./run-checks";
import { validateConfig } from "./validate-config";

export function createHealth(options: CreateHealthOptions): Health {
  // Fail fast: Validate configuration immediately upon creation
  validateConfig(options);

  // Allow teams to override default policies if business rules differ
  const calculateStatus = options.calculateStatus ?? defaultCalculateStatus;
  const buildReport = options.buildReport ?? defaultBuildReport;

  return {
    async run() {
      const results = await runChecks(options.checks, options.defaultTimeoutMs);
      const status = calculateStatus(results);
      return buildReport(results, status);
    }
  };
}

Express adapter

import type { Express, Request, Response } from "express";
import type { Health } from "../types/index"; // Adjust path to your core block

export function registerExpressHealthRoute(app: Express, health: Health, path = "/health") {
  app.get(path, async (_req: Request, res: Response) => {
    const report = await health.run();

    // 503 for unhealthy (pull from load balancer)
    // 200 for healthy/degraded (keep in rotation, let the JSON report show the degraded state)
    const statusCode = report.status === "unhealthy" ? 503 : 200;

    res.status(statusCode).json(report);
  });
}

Fastify adapter

import type { FastifyInstance } from "fastify";
import type { Health } from "../types/index";
export function registerFastifyHealthRoute(app: FastifyInstance, health: Health, path = "/health") {
  app.get(path, async (_request, reply) => {
    const report = await health.run();
    const statusCode = report.status === "unhealthy" ? 503 : 200;

    reply.code(statusCode).send(report);
  });
}

Hono adapter

import type { Hono } from "hono";
import type { Health } from "../types/index";

export function registerHonoHealthRoute(app: Hono, health: Health, path = "/health") {
  app.get(path, async (c) => {
    const report = await health.run();
    const statusCode = report.status === "unhealthy" ? 503 : 200;

    return c.json(report, statusCode);
  });
}

Configuration

createHealth takes one object:

OptionTypeDefaultDescription
checksHealthCheck[]RequiredChecks to run. Must not be empty.
defaultTimeoutMsnumber5000Timeout for checks without timeoutMs.
calculateStatusStatusCalculatorBuilt-inMaps results to healthy, degraded, or unhealthy.
buildReportReportBuilderBuilt-inBuilds the report returned by run(). Must return HealthReport.

Each HealthCheck has these fields:

FieldTypeRequiredDescription
namestringYesUnique name used in the report.
criticalbooleanYesWhen true, a failure makes the whole report unhealthy.
run() => Promise<void>YesThrow to fail the check. Return normally to pass.
timeoutMsnumberNoPer-check timeout. Overrides defaultTimeoutMs.
messagestringNoText included in the result.

Usage

Express

import express from "express";
import { createHealth } from "@/blocks/health-check/core/create-health";
import { registerExpressHealthRoute } from "@/blocks/health-check/adapters/express";

const app = express();

const health = createHealth({
  checks: [
    {
      name: "postgres",
      critical: true,
      async run() {
        await db.query("SELECT 1");
      }
    },
    {
      name: "redis",
      critical: false,
      timeoutMs: 2_000,
      async run() {
        await redis.ping();
      }
    }
  ]
});

registerExpressHealthRoute(app, health);

Fastify

import Fastify from "fastify";
import { createHealth } from "@/blocks/health-check/core/create-health";
import { registerFastifyHealthRoute } from "@/blocks/health-check/adapters/fastify";

const app = Fastify();

const health = createHealth({
  checks: [
    {
      name: "database",
      critical: true,
      async run() {
        await db.query("SELECT 1");
      }
    }
  ]
});

registerFastifyHealthRoute(app, health);

await app.listen({ port: 3000 });

Hono

import { Hono } from "hono";
import { createHealth } from "@/blocks/health-check/core/create-health";
import { registerHonoHealthRoute } from "@/blocks/health-check/adapters/hono";

const app = new Hono();

const health = createHealth({
  checks: [
    {
      name: "database",
      critical: true,
      async run() {
        await db.query("SELECT 1");
      }
    }
  ]
});

registerHonoHealthRoute(app, health);

export default app;

Custom status logic

const health = createHealth({
  checks,
  calculateStatus(results) {
    if (results.every((result) => result.status === "healthy")) return "healthy";
    if (results.some((result) => result.critical && result.status === "unhealthy")) {
      return "unhealthy";
    }
    return "degraded";
  }
});

Custom report fields

buildReport must return a HealthReport. If you need extra fields for your own endpoint, add them after run():

app.get("/health", async (_req, res) => {
  const report = await health.run();

  res.status(report.status === "unhealthy" ? 503 : 200).json({
    ...report,
    version: process.env.APP_VERSION ?? "dev"
  });
});

Do not return extra fields from a custom buildReport without widening the type. They are not part of the HealthReport contract and will fail type checking.

API reference

createHealth

function createHealth(options: CreateHealthOptions): Health;

Validates the config immediately. It throws when checks is missing or empty, a check name is empty or duplicated, a check has no run function, or a timeout is not a positive number.

health.run

async function run(): Promise<HealthReport>;

Runs every check concurrently and waits for all of them. One check cannot hang the request because each check is bounded by its timeout.

HealthReport

interface HealthReport {
  status: "healthy" | "degraded" | "unhealthy";
  timestamp: string;
  uptime: number; // seconds
  checks: HealthCheckResult[];
}

interface HealthCheckResult {
  name: string;
  critical: boolean;
  status: "healthy" | "unhealthy";
  duration: number; // milliseconds
  message?: string;
  error?: string;
}

error is a string, not an Error object, so stack traces do not reach the response.

Behavior

  • All checks run at the same time with Promise.all.
  • Each check gets its own timeout. The default is 5 seconds.
  • A critical failure sets the report to unhealthy.
  • A non-critical failure sets it to degraded.
  • If every check passes, the report is healthy.
  • The adapter maps only unhealthy to 503. degraded stays on 200 so the instance keeps serving traffic.

When not to use it

  • You only need a fixed { ok: true } liveness endpoint. A route is enough.
  • You need metrics or tracing. This block returns a snapshot, not a time series.
  • You need to run checks in the background. This block runs them when health.run() is called.

On this page