» Node.js: Build a REST API with Express » 2. Development » 2.2 Health Endpoint

Health Endpoint

A health endpoint refers to a specific endpoint or route provided by the server that is used to determine the health or status of the server or application. This endpoint is typically used for monitoring and management purposes, allowing external systems or monitoring tools to check whether the API server is functioning properly.

Modify src/app.ts:

@@ -3,8 +3,8 @@ import express, { Request, Response } from "express";
 const app = express();
 const port = process.env.PORT || 3000;
 
-app.get("/ping", (req: Request, res: Response) => {
-  res.json({ message: "pong" });
+app.get("/", (req: Request, res: Response) => {
+  res.json({ status: "ok" });
 });
 
 app.listen(port, () => {

The response of endpoint /:

{"status":"ok"}

Optional:
If you want to include CPU or memory data in the health endpoint response, you would need to gather this information from the system where your Node.js application is running.

Modify src/app.ts [optional]:

@@ -1,10 +1,21 @@
 import express, { Request, Response } from "express";
+import os from "os";
 
 const app = express();
 const port = process.env.PORT || 3000;
 
-app.get("/ping", (req: Request, res: Response) => {
-  res.json({ message: "pong" });
+app.get("/", (req: Request, res: Response) => {
+  const cpuUsage = os.cpus();
+  const totalMemory = os.totalmem();
+  const freeMemory = os.freemem();
+  res.json({
+    status: "ok",
+    cpuUsage,
+    totalMemory,
+    totalMemory_MB: totalMemory / 1024 / 1024,
+    freeMemory,
+    freeMemory_MB: freeMemory / 1024 / 1024,
+  });
 });
 
 app.listen(port, () => {

The response is something like this:

{
  "status": "ok",
  "cpuUsage": [
    {
      "model": "Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz",
      "speed": 2600,
      "times": {
        "user": 27721500,
        "nice": 0,
        "sys": 15033140,
        "idle": 188708050,
        "irq": 0
      }
    },
    {
      "model": "Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz",
      "speed": 2600,
      "times": {
        "user": 391930,
        "nice": 0,
        "sys": 406990,
        "idle": 231839750,
        "irq": 0
      }
    },
    ...
  ],
  "totalMemory": 17179869184,
  "totalMemory_MB": 16384,
  "freeMemory": 1339666432,
  "freeMemory_MB": 1277.60546875
}