How to connect to the Ethereum network using NodeJS

Gaurav Agrawal
March 19, 2020


NodeJS grew exponentially in the last 10 years. The Ethereum ecosystem also has extensive support for NodeJS language. In this article, we will see how to connect to the Ethereum network using NodeJS, specifically, in this tutorial, we will get the latest Ethereum Block number.

[image here]

  • Ethereum Node (We will use QuikNode’s free version)
  • NodeJS installed in your system
  • Install Web3 (A NodeJs wrapper for Ethereum node APIs)
  • A text editor

Ethereum blockchain network is a network of Ethereum nodes. These nodes expose APIs using which we can interact with the Ethereum network.

So we need a running Ethereum node, therefore, we will use QuikNode for this. Just sign up here and get the node URL.

Installing the web3 package

Next, let's get the web3 package installed - this is the package that lets you interact with the ethereum blockchain. You can install it with npm:

$ npm install web3

You can also use yarn:

$ yarn add web3

All good? Let's proceed.

Connecting via JS

Now let's create a short script to fetch the block height from our node. You can copy/paste this into your code editor:

var http = require('http');
var Web3 = require('web3');
var provider = 'ADD_YOUR_ETHEREUM_NODE_URL';
var web3Provider = new Web3.providers.HttpProvider(provider);
var web3 = new Web3(web3Provider);web3.eth.getBlockNumber().then((result) => {
  console.log("Latest Ethereum Block is ",result);

As you can see, we are importing web3 and setting our Ethereum node URL. Then simply calling getBlockNumber API provided by theweb3 library.

Save this code snippet in a file index.js we're going to run this very shortly.

Confirm it's working

Run the file using node command and you will see the latest Ethereum blockchain:

$ node index.js

You should see the following:

[image here]

That’s it you have connected through Ethereum network using NodeJs. You can check out more APIs provided web3 to build complex applications on Ethereum. 
Gaurav Agrawal & Coinmonks publication ( and Editor — Coinmonks, Crowdbotics, and QuikNode

Related articles

All set for your QuikNode?