Node.js: Getting current git commit information on an app

I often wonder what are the last changes that are live on my production APIs. I would specifically want to know which is the last git commit live on that particular app.

If you have automated deployment setup and use standard procedures like git flow, it’s easy — just check out what’s on the master branch. But what if the last build failed and my latest changes to master are not actually in production? What if you push all your development changes to master branch (which is a bad practice) and manually deploy periodically? Being able to get the latest commit information on an app via api could be useful.

We can retrieve the latest git commit hash by reading the output of this git command:

git rev-parse HEAD

Let’s quickly write a function to run that command and get us the output as string.

Now we can add this commit hash to a special endpoint on our app.

The code example is from a Koa app with koa-router, written in TypeScript. But the code should be adaptable to your framework of choice quite easily.

Once we hook this view function to our app’s router and then visit the endpoint, we should be able to see the git commit hash:

Getting more info

If we want to get more information about our git commit, there’s a nice npm package git-last-commit which can be used to get more detailed data. Let’s install it.

npm i git-last-commit

Now let’s write another function that wraps this module in a promise.

And then update the API handler:

Since we return a promise from getGitCommit(), we have to await it’s response here.

If we visit the endpoint again, the response should look like this:

Both my first approach and this npm module uses the git command line tool and parses it’s outputs. So it’s a requirement that you have git installed on your server to be able to retrieve these information.

Publishing git commit information publicly is definitely not a good idea. Even if we have to do it for monitoring or any other purposes, I would make sure the data is accessed securely and perhaps from within a private network.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store