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.
1. Install ServerCN dependencies(Optional)
- HTTP Status Codes:
npx servercn add http-status-codesDocumentation: HTTP Status Codes
- Api Response Handler:
npx servercn add response-formatterDocumentation: Api Response Handler
- Api Error Handler:
npx servercn add error-handlerDocumentation: Api Error Handler
- Async Handler:
npx servercn add async-handlerDocumentation: Async Handler
2. Install this component
npx servercn add health-checkBasic Implementation
1. MVC Structure
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;2. Feature Structure
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
1. Basic Health Check
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
}
}2. Detailed Health Check
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
}
}
}
}4. Health Check with External Services
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";
}
}5. Using Async Handler
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
Basic 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...Multiple Health Endpoints
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
- Keep it fast - Health checks should respond quickly (< 100ms)
- Don't include sensitive data - Avoid exposing internal details
- Use appropriate status codes - 200 for healthy, 503 for unhealthy
- Monitor dependencies - Check critical services (DB, Redis, etc.)
- Set up alerts - Configure alerts based on health check failures
- Version your API - Include version information in detailed checks
Response Format
Healthy Response (200)
{
"success": true,
"message": "Service is healthy",
"statusCode": 200,
"data": {
"status": "healthy",
"timestamp": "2024-01-15T10:30:00.000Z",
"uptime": 3600.5
}
}Unhealthy Response (503)
{
"success": false,
"message": "Service is unhealthy",
"statusCode": 503,
"data": {
"status": "unhealthy",
"timestamp": "2024-01-15T10:30:00.000Z",
"checks": {
"database": "disconnected"
}
}
}Security Considerations
- Rate limiting - Consider rate limiting health check endpoints
- Authentication - Optionally protect detailed endpoints
- IP whitelisting - Restrict access to monitoring IPs if needed
- 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