Implement health check for Node application

0
60
Implement health check for Node application
Implement health check for Node application

We always need to monitor for our applications, so we can quickly react when something happens. I will show you a simple way to implement a health check for Node application in this post.

To make it simple, we will implement health check for Node application using ExpressJS. Let’s start by quickly creating an Express application.

$ mkdir add-healthcheck

$ cd add-healthcheck

$ npm init -y

$ touch index.js

We need to install Express dependency:

$ npm i -S express

Then add following basic code for the index.js

// file: index.js

const express = require('express');

const app = express();

app.get(`/`, (req, res) => {
    res.send('blog.petehouston.com - Implement health check for Node application');
});

const SERVER_PORT = process.env.PORT || 3000;

app.listen(SERVER_PORT,() => {
    console.log(`Server started at :${SERVER_PORT}`);
});

In order to determine if the application is running okay or not, we need to make sure that whenever a request is made to the web app, it should respond properly; in case, an error is returned back, that means something just goes wrong.

With that in mind, we should make the health check route as much simple as we can. For this demo, this is what we could write:

// file: index.js

app.get(`/health`, (req, res) => {
    try {
        res.send({
            message: 'OK',
            timestamp: Date.now(),
        });
    } catch (e) {
        res.status(503).send({
            message: e,
        });
    }
});

You can start the local server and access the /health route in browser to confirm the message.

In real-world application, it will look more complicated, ex. if the Express web app has a connection to database, then the health check request needs to confirm a database status.

So code for the health check route could be something similar to this:

# file: index.js

// get a connection to database
const databaseConnection = require('./databaseConnection');
app.get(`/health`, async (req, res) => {
    try {
        // ping to database
        await databaseConnection.ping()

        res.send({
            message: 'OK',
            timestamp: Date.now(),
        });
    } catch (e) {
        res.status(503).send({
            message: e,
        });
    }
});

Basically, any component or service that is required to make your web app running properly should be included in the health check.

That’s it, I’ve shown you how to Implement health check for Node application.

You can check demo code here:

Have fun!