Thanks to visit codestin.com
Credit goes to servercn.vercel.app

Health Check

The Health Check component provides production-ready endpoints for monitoring your API's status, system health, and service availability. Essential for load balancers, monitoring systems, and deployment tools.


Installation Guide

npx servercn-cli add health-check

Basic Implementation

src/controllers/health.controller.ts
import { Request, Response } from "express";
import { ApiResponse } from "../utils/api-response";
 
export const healthCheck = async (_req: Request, res: Response) => {
  return ApiResponse.Success(res, "Service is healthy", {
    status: "healthy",
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
};
 
export const detailedHealthCheck = async (_req: Request, res: Response) => {
  const healthData = {
    status: "healthy",
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: process.env.NODE_ENV || "development",
    version: process.env.npm_package_version || "1.0.0",
    memory: {
      used:
        Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100,
      total:
        Math.round((process.memoryUsage().heapTotal / 1024 / 1024) * 100) / 100,
      unit: "MB"
    },
    cpu: {
      usage: process.cpuUsage()
    }
  };
 
  return ApiResponse.Success(res, "Service is healthy", healthData);
};

src/routes/health.routes.ts
import { Router } from "express";
import {
  healthCheck,
  detailedHealthCheck
} from "../controllers/health.controller";
 
const router = Router();
 
router.get("/", healthCheck);
router.get("/detailed", detailedHealthCheck);
 
export default router;

src/app.ts
import express, { type Application } from "express";
import healthRoutes from "./routes/health.routes";
 
const app: Application = express();
 
app.use(express.json());
 
// Health check routes (usually placed early)
app.use("/api/health", healthRoutes);
 
// Other routes...

Usage Examples

Simple endpoint that returns service status:

{
  "success": true,
  "message": "Service is healthy",
  "statusCode": 200,
  "data": {
    "status": "healthy",
    "timestamp": "2024-01-15T10:30:00.000Z",
    "uptime": 3600.5
  }
}

Include system information:

{
  "success": true,
  "message": "Service is healthy",
  "statusCode": 200,
  "data": {
    "status": "healthy",
    "timestamp": "2026-01-09T14:15:21.360Z",
    "uptime": 155.729376,
    "environment": "development",
    "version": "1.0.0",
    "memory": {
      "used": 41.59,
      "total": 44.46,
      "unit": "MB"
    },
    "cpu": {
      "usage": {
        "user": 3031000,
        "system": 812000
      }
    }
  }
}

File & Folder Structure

Loading files...

Installation

npx servercn-cli add health-check