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.

Features

  • Basic health check - Simple endpoint to verify service is running
  • Detailed health check - System information including memory, CPU, and uptime
  • Database connectivity check - Optional database health verification
  • Customizable - Easy to extend with additional health checks
  • Production-ready - Standardized responses for monitoring tools

Installation Guide

This component requires additional ServerCN components.

👉 Note: You do not need to install any servercn dependencies manually. Installing this component will automatically install all required servercn dependencies. Manual installation is optional if you prefer to manage dependencies yourself.

  • HTTP Status Codes:
npx servercn add http-status-codes

Documentation: HTTP Status Codes

  • Api Response Handler:
npx servercn add response-formatter

Documentation: Api Response Handler

  • Api Error Handler:
npx servercn add error-handler

Documentation: Api Error Handler

  • Async Handler:
npx servercn add async-handler

Documentation: Async Handler

npx servercn add health-check

Basic Implementation

Create health check controller in 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()
  });
};

Create routes in src/routes/health.routes.ts:

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

For feature-based architecture, place controller in src/modules/health/health.controller.ts:

import { Request, Response } from "express";
import { ApiResponse } from "../../shared/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()
  });
};

Usage Examples

Simple endpoint that returns service status:

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()
  });
};

Response:

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

Include system information:

import { ApiResponse } from "../utils/api-response";
 
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);
};

Response:

{
  "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
      }
    }
  }
}

Check external service dependencies:

export const healthCheckWithServices = async (_req: Request, res: Response) => {
  const checks = {
    status: "healthy",
    timestamp: new Date().toISOString(),
    checks: {
      database: await checkDatabase(),
      redis: await checkRedis(),
      externalApi: await checkExternalApi()
    }
  };
 
  // Determine overall health
  const allHealthy = Object.values(checks.checks).every(
    status => status === "healthy"
  );
 
  if (!allHealthy) {
    checks.status = "degraded";
    return ApiResponse.Error(res, "Service is degraded", checks);
  }
 
  return ApiResponse.Success(res, "Service is healthy", checks);
};
 
async function checkDatabase(): Promise<string> {
  try {
    // Your database check logic
    return "healthy";
  } catch {
    return "unhealthy";
  }
}
 
async function checkRedis(): Promise<string> {
  try {
    // Your Redis check logic
    return "healthy";
  } catch {
    return "unhealthy";
  }
}
 
async function checkExternalApi(): Promise<string> {
  try {
    // Your external API check logic
    return "healthy";
  } catch {
    return "unhealthy";
  }
}

With async handler for better error handling:

import { AsyncHandler } from "../utils/async-handler";
 
export const healthCheck = AsyncHandler(
  async (_req: Request, res: Response) => {
    return ApiResponse.Success(res, "Service is healthy", {
      status: "healthy",
      timestamp: new Date().toISOString(),
      uptime: process.uptime()
    });
  }
);

Route Setup

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...
src/routes/health.routes.ts
import { Router } from "express";
import {
  healthCheck,
  detailedHealthCheck,
  healthCheckWithDB
} from "../controllers/health.controller";
 
const router = Router();
 
router.get("/", healthCheck);
router.get("/detailed", detailedHealthCheck);
router.get("/db", healthCheckWithDB);
 
export default router;

Best Practices

  1. Keep it fast - Health checks should respond quickly (< 100ms)
  2. Don't include sensitive data - Avoid exposing internal details
  3. Use appropriate status codes - 200 for healthy, 503 for unhealthy
  4. Monitor dependencies - Check critical services (DB, Redis, etc.)
  5. Set up alerts - Configure alerts based on health check failures
  6. Version your API - Include version information in detailed checks

Response Format

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

Security Considerations

  1. Rate limiting - Consider rate limiting health check endpoints
  2. Authentication - Optionally protect detailed endpoints
  3. IP whitelisting - Restrict access to monitoring IPs if needed
  4. Information disclosure - Don't expose sensitive system information

Common Use Cases

  • Load balancer health checks - Verify service availability
  • Monitoring systems - Track service uptime and performance
  • Deployment verification - Confirm successful deployments
  • Auto-scaling - Determine when to scale services
  • Incident response - Quick status verification during outages

File & Folder Structure

Select a file to view its contents

Installation

npx servercn add health-check