From be5f5ff3f00ff79234aefefbc978530d5c5c87d9 Mon Sep 17 00:00:00 2001 From: Chneemann Date: Sat, 15 Aug 2026 12:36:08 +0200 Subject: [PATCH] feat(api): add dynamic health check endpoint with db ping --- app/api/health/route.ts | 59 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 app/api/health/route.ts diff --git a/app/api/health/route.ts b/app/api/health/route.ts new file mode 100644 index 0000000..0dc5344 --- /dev/null +++ b/app/api/health/route.ts @@ -0,0 +1,59 @@ +/** + * @file api/health/route.ts + * @description API route handler performing a database health check by executing a test query and returning the system status. + */ + +import { db } from "@/db"; +import { sql } from "drizzle-orm"; +import { NextResponse } from "next/server"; + +export const dynamic = "force-dynamic"; + +/** + * Handles GET requests to check the health and database connectivity of the application. + * Executes a lightweight SQL query and returns a JSON response indicating whether the service is healthy or unhealthy. + * + * @async + * @returns {Promise} A JSON response containing status details, database connectivity state, error messages if applicable, and a timestamp. + */ +export async function GET() { + try { + await db.execute(sql`SELECT 1`); + + return NextResponse.json( + { + status: "healthy", + database: "connected", + timestamp: new Date().toISOString(), + }, + { + status: 200, + headers: { + "Cache-Control": "no-store, max-age=0", + }, + }, + ); + } catch (error) { + console.error("Health check failed:", error); + + return NextResponse.json( + { + status: "unhealthy", + database: "disconnected", + error: + process.env.NODE_ENV === "development" + ? error instanceof Error + ? error.message + : "Unknown error" + : "Database connection failed", + timestamp: new Date().toISOString(), + }, + { + status: 500, + headers: { + "Cache-Control": "no-store, max-age=0", + }, + }, + ); + } +}