0
0
Node.jsframework~5 mins

Health check endpoints in Node.js

Choose your learning style9 modes available
Introduction

Health check endpoints help you quickly see if your app is running well. They tell you if the server is alive and ready to handle requests.

You want to monitor if your web server is up and responding.
You need to check if your app is ready before sending traffic to it.
You want to automate alerts if your service goes down.
You use cloud services or load balancers that require a health check URL.
You want to debug if your app is stuck or crashed.
Syntax
Node.js
app.get('/health', (req, res) => {
  res.status(200).send('OK');
});

This example uses Express.js to create a simple GET endpoint at '/health'.

The endpoint returns a 200 status with a simple message to show the app is healthy.

Examples
Basic health check returning 'OK' with status 200.
Node.js
app.get('/health', (req, res) => {
  res.status(200).send('OK');
});
Health check returning JSON with status and uptime in seconds.
Node.js
app.get('/health', (req, res) => {
  const uptime = process.uptime();
  res.json({ status: 'ok', uptime: uptime });
});
Health check that returns 503 if a service like a database is down.
Node.js
app.get('/health', (req, res) => {
  // Here you could check database or other services
  const dbConnected = true;
  if (dbConnected) {
    res.status(200).send('Healthy');
  } else {
    res.status(503).send('Service Unavailable');
  }
});
Sample Program

This Node.js program uses Express to create a server with a health check endpoint at '/health'. When you visit this URL, it returns a JSON object showing the app status and how long it has been running.

Node.js
import express from 'express';

const app = express();
const port = 3000;

app.get('/health', (req, res) => {
  const uptime = process.uptime();
  res.json({ status: 'ok', uptime: uptime.toFixed(2) });
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

Keep health check endpoints simple and fast to avoid slowing down your app.

Use status codes: 200 means healthy, 503 means service unavailable.

Consider checking important dependencies like databases or APIs in your health check.

Summary

Health check endpoints show if your app is alive and ready.

They usually return a simple message or JSON with status info.

Use them to help monitor and manage your app in real time.