How to implement a health check in Node.js
Tags: node, webdev
Published: 2022-06-08 21:18:51

**Written by [Precious Luke](https://blog.logrocket.com/author/preciousluke/)✏️**

Health is really important. There is a popular saying that health is wealth — his is true even in software engineering. Yes! Like living things, an application can be broken too if we do not take care of it. 

Health checks in software help us identify inefficiencies in our applications to better maintain them. Much like how we see a doctor to know if anything is wrong with us, right, the same principle applies to software as we pay attention to the server or response time, as one example. 

In this article, we will examine how to do a health check in a Node.js application.

*   [Why you need to have health checks](#why-you-need-to-have-health-checks)
*   [Implementing a health check in Node.js](#implementing-a-health-check-in-node-js)
    *   [Adding a health check route](#adding-a-health-check-route)
    *   [Registering the healthcheck route](#registering-the-healthcheck-route)
    *   [Adding response time](#adding-response-time)
*   [Alternative tools](#alternative-tools)

## Requirements

We will implement a basic Node.js health check. Here’s what’s necessary to follow along:

*   [Node.js](https://nodejs.org/en/) installed on your machine (this comes with [Node package manager](https://www.npmjs.com/))
*   An integrated development environment (IDE)

## Why you need to have health checks <a name="why-you-need-to-have-health-checks">

As we have already mentioned in the introduction; health is wealth. Before we jump into how to implement health check in Node.js, let’s talk about its importance and why you should get into the habit of performing these checks. 

We first need to acknowledge that the availability of software or functionality is extremely important. Routine health checking of the availability of APIs, for instance, helps you learn of crucial issues and remediate them as quickly as possible. 

If downtime occurs, the application owner can be informed immediately so that there is a speedy resolution to it. 

Health checks become even more important as the infrastructure of our software grows, and the need to make sure that all microservices and endpoints are working flawlessly becomes more vital for the apps we manage. 

Some of the things we check when considering the health of software in any programming language or stack are the response time of a server when a request is made and how the server connects to the database (if there is one). 

Another reason why a health check is necessary is to maintain the availability of your services. Your application or product should not be seen as the one that has the most downtime among its competitors — it is bad for business, and a good name is better than fortune, as they say.

## Implementing a health check in Node.js <a name="implementing-a-health-check-in-node-js">

We will now look at how to implement a basic health check in Node.js. 

I will be using an application I’ve built. [Here is a link](https://blog.logrocket.com/building-structuring-node-js-mvc-application/) to the tutorial for it. The Github code can be found [here](https://github.com/bigpreshy/mvc). You can clone or download it from [here](https://github.com/bigpreshy/mvc). 

Use `git clone` to clone the repository into your own machine:

```
git clone https://github.com/bigpreshy/mvc
```

Then move into the folder by doing this:

```
cd mvc
```

The package.json file should look like this: ![Package Json Screenshot](https://blog.logrocket.com/wp-content/uploads/2022/05/package-json-screenshot.png) After that, run this command to install all the dependencies (packages) used in the application:

```
npm install
```

After this has been completed, run:

```
npm run develop
```

On your browser, go to http://localhost:4111/login (there are other routes like _/register/dashboard_). ![Nodejs MVC](https://blog.logrocket.com/wp-content/uploads/2022/05/node-js-mvc.png) Now everything is running. You can follow the MVC tutorial to connect to [MongoDB Atlas](https://www.mongodb.com/cloud/atlas)

### Adding a health check route

To add a basic health check that performs checks (server health and run time, etc.), add healthchecker.js in our route folder and add the following code:

```javascript
const express = require("express");
const router = express.Router({});
router.get('/', async (_req, res, _next) => {

    const healthcheck = {
        uptime: process.uptime(),
        message: 'OK',
        timestamp: Date.now()
    };
    try {
        res.send(healthcheck);
    } catch (error) {
        healthcheck.message = error;
        res.status(503).send();
    }
});
// export router with all routes included
module.exports = router;
```

What we’ve done here is added another route, and this route has a `healthcheck` object that has three properties (uptime**_,_** message**_,_** and timestamp) which have respective values `process.uptime()`**,** `OK`**,** and `Date.now()`. 

We also have a [try catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch), which executes the code in the try block. If an exception exists, it responds with an error (the message value in the `healthcheck` object becomes the error) and sends a status of [503](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503). 

Finally, we have to export the module (router), hence the `module.exports = router;` at the end of the file.

### Registering the healthcheck route

After we have created the route, go ahead edit the index.js file. Just add this line of code:

```
app.use('/healthcheck', require('./routes/healthchecker'));
```

After that, your full index.js file will look like this:

```javascript
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const session = require('express-session');
dotenv.config();
const passport = require("passport");
const { loginCheck } = require("./auth/passport");
loginCheck(passport);
// Mongo DB conncetion
const database = process.env.MONGOLAB_URI;
mongoose
  .connect(database, { useUnifiedTopology: true, useNewUrlParser: true })
  .then(() => console.log("e don connect"))
  .catch((err) => console.log(err));
app.set("view engine", "ejs");
//BodyParsing
app.use(express.urlencoded({ extended: false }));
app.use(session({
    secret:'oneboy',
    saveUninitialized: true,
    resave: true
  }));

app.use(passport.initialize());
app.use(passport.session());
//Routes
app.use("/", require("./routes/login"));
app.use('/healthcheck', require('./routes/healthchecker'));

const PORT = process.env.PORT || 4111;
app.listen(PORT, console.log("Server has started at port " + PORT));
```

Take note of how our routes are registered. It is added right after our `passport.session()` and `passport.initialize()` methods. 

After that, stop the server and rerun `npm run develop`, then go to http://localhost:4111/healthcheck, it will show this: ![Local Host Healthcheck](https://blog.logrocket.com/wp-content/uploads/2022/05/local-host-healthcheck.png) 

This has our uptime (how long our server has been up and running since it started), an "OK" message that indicates that everything is good, and a timestamp is included, too.

### Adding response time

Another thing to check is response time — how long it takes your server to respond to requests. 

To do this, we are going to be adding the following `process.hrtime()` method as a value to the `processtime` property in the `healthcheck` object that is our healthchecker.js file in our route folder. 

Your healthchecker.js should look like this: ![Healthcheckerjs Screenshot Example](https://blog.logrocket.com/wp-content/uploads/2022/05/healthchecker-js-screenshot-example.png) 

Refreshing your server and revisiting http://localhost:4111/healthcheck will give you this. It will now have the `responsetime` property with the value recorded in nanoseconds: ![Local Host Response Time Uptime](https://blog.logrocket.com/wp-content/uploads/2022/05/local-host-response-time-uptime.png)

## Alternative tools

It is also worth noting that there are services that have been built over the years that routinely check the health of our applications (not just Node.js, but applications in other stacks too). I usually use [https://uptimerobot.com/](https://uptimerobot.com/) . 

There are others. [LogRocket](https://logrocket.com/) does this for frontend monitoring, and there are also [Freshping](https://app.freshping.io/), [Uptime](https://uptime.com/go/home), [Logicmonitor](https://www.logicmonitor.com/),, all of which should tell you that the health of applications is really important!

## Conclusion

In this article, we have discussed what health checks entail and why we need to consider them in your applications for easy and quick issue resolution. 

Furthermore, we looked at how health checks can be implemented in Node.js with a sample project. This [project](http://github.com/bigpreshy/mvc) is simply a Model-view-controller Node.js based project that handles user registration and login using Mongo DB as a database. 

Here are some of the things we checked for: the response time of the server, the uptime of the server, the status code of the server (as long as it is 200, we are going to get an "OK" message), and the timestamp of the server. 

You need to think about health of your application when you are developing. This helps you to monitor closely what is happening and if eventually, something unforeseen happens, you would know where to look.

---
##200’s only :heavy_check_mark: Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, [try LogRocket.](https://logrocket.com/signup/)

[![LogRocket Sign Up](https://blog.logrocket.com/wp-content/uploads/2019/12/network-request-filter-2-1.png)](https://logrocket.com/signup/)

[LogRocket](https://logrocket.com/signup/) is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.