All Articles

Sample NodeJS app to query the Ethereum blockchain

Had a discussion last night with some friends and was really curious how to develop applications utilising blockchain technology. I found the Ethereum API a few months back but I was not clear on how to start until last night.

Eric, a former colleague, blogged about a sample on how to do it in Java using Spring Boot and Thymeleaf. One key thing in his blog was the use of the Infura API rather than spinning up a node to communicate with the Ethereum blockchain. Check out his blog “My first foray into the world of blockchain”.

Inspired by all of this, I tried web3js which Eric suggested. web3js, an Ethereum Javascript API, is developed by the Ethereum team. I came up with a basic nodeJS sample below using web3js. It’s basically the nodeJS version of what Eric has done in his blog. Really simple stuff but I needed to figure out things for a few hours to get it running.

var BigNumber = require('bignumber.js');
var Web3 = require('web3')

var web3 = new Web3(new Web3.providers.HttpProvider(process.env.API_URL));

var balance = web3.eth.getBalance(process.env.ACCOUNT, function (error, result) {
    if (!error) {
	console.log(web3.utils.fromWei(new BigNumber(result), 'ether'));
    } else {

Source code is available in my github

Steps to run the sample app

  1. Install all dependencies using npm
npm install
  1. Configure. Create a .env file with the ff. contents. You can register in to get an API URL with an access key. Infura can save you the hassle of spinning up your own node. Account configured below is Ethereum’s founder Vitalik Buterin’s account. (got this from Eric’s blog)
API_URL=<access key>

You can also get some accounts to query here

  1. And finally, run the application

    node index.js


Check if the result is the same as the current value


Some references:

This video by Conor Svensson, founder of web3j can be useful to get you up to speed on understanding Blockchain.

If you have any questions about the sample application or have some ideas about blockchain, feel free to start a discussion below.