Marketplace has launched, further enabling blockchain developers! Learn more

How to connect to Ethereum network with ethers.js

September 09, 2022

Overview

When someone thinks of developing a dApp the first tool that comes to their mind is web3.js which is pretty common because of its popularity in the community and wide use cases, dApp development has been consistently growing and there are a lot of developers who want to learn dApp development. The web3.js library is sometimes not suitable because of it’s heavy package size. So here the ethers.js library comes into the picture, ethers.js is an alternative to web3.js library and it is very compact as compared to web3.js. It is only 88kb when compressed, ethers.js is open source and very well tested, it is maintained by dedicated contributors.

ethers.js is well suited for those who are relatively new to the dApp/blockchain development as it is very easy to use. Lots of new companies and projects are preferring ethers.js over other libraries like web3.js because of its performance profile with regards to the browser. Typescript has been gaining a lot of popularity lately, so if you’re amongst the typescript aficionados - don’t worry makers of ethers.js saw the future and made it future proof with will full Typescript source. 

In this article, we'll cover installing ethers.js, use it to connect to a web3 provider, and get the latest block height.

Prerequisites
  • NodeJS installed on your system
  • A text editor
  • Terminal aka Command Line

Installing ethers.js library

First, let's make sure we have NodeJS installed. Pretty simple, open a terminal and run:

installing ethers js library

Copy
$ node -v

if not installed, you can download the LTS version of NodeJS from the official website.

If you want to use ethers.js in the browser simply add the following script tag in your HTML file:

installing ethers js library

Copy
<script charset="utf-8"
        src="https://cdn.ethers.io/scripts/ethers-v4.min.js"
        type="text/javascript">
</script> 

OR

Now let's install the ethers.js package, which will help us to connect to the ethereum network and build awesome dApp frontends. You can install it with npm from the command line:

installing ethers js library

Copy
$ npm install --save ethers 

The most common issue at this step is an internal failure with `node-gyp`. You can follow node-gyp installation instructions here.

Note: You will need to have your python version match one of the compatible versions listed in the instructions above if you encounter the node-gyp issue. 

Another common issue is a stale cache, clear your npm cache by simply typing the below into your terminal:

installing ethers js library

Copy
$ npm cache clean

If everything goes right and ethers.js get installed correctly and you’re halfway there!

Booting our Ethereum node

For our purposes today, we could use pretty much any Ethereum client, such as Geth or OpenEthereum (fka Parity). Since that is a bit too involved for just querying for block height, we'll just grab a free endpoint from QuickNode to make this easy. After you've created your free ethereum endpoint, copy your HTTP Provider endpoint:

A screenshot of the Quicknode Ethereum endpoint Getting Started page with HTTP link and WSS


You'll need this later, so copy it and save it.

Connecting via ethers

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

connecting via ethers

Copy
var ethers = require('ethers');  
var url = 'ADD_YOUR_ETHEREUM_NODE_URL';
var customHttpProvider = new ethers.providers.JsonRpcProvider(url);
customHttpProvider.getBlockNumber().then((result) => {
    console.log("Current block number: " + result);
});

So go ahead and replace `ADD_YOUR_ETHEREUM_NODE_URL` with the http provider from the section above. 

A quick explanation of the code above - we are importing the ethers library we installed earlier (line 1), setting our Ethereum node URL (line 2), instantiating an ethers JsonRpcProvider instance (line 3). Finally, we're calling getBlockNumber on the ethers json rpc object and waiting for a successful result from the server then logging the result to the console (lines 4-6).

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

Confirm it's working

Run the script we just made using the node command and you will see the latest Ethereum blockchain:

confirm it s working

Copy
$ node index.js

You should see the following:

Output

That’s it! You have connected to the Ethereum network using ethers.js. You can check out ethers GitHub for more information or see other ethers.js projects. If you want to use this in a front-end application, you can configure webpack to compile it into something suitable for a browser.

Subscribe to our newsletter for more articles and guide on Ethereum. If you have any feedback, please feel free to reach out to us via Twitter and you can always chat with us if you have a question via our community server on Discord, thanks :)

Bonus

If you want to use ethers.js with truffle there is a package to make it possible ethers-cli developed by the same developer who developed ethers.js, It replaces much of truffle, and has a TestRPC included along with the ethers hook-ups to make it all work.

If you wanted to init the provider for all the wallet instances, it’s really simple with ethers simply add the below in your code:

bonus

Copy
const provider = ethers.getDefaultProvider();

Related articles 36

How to Access Bitcoin Mempool
Published: Aug 16, 2021
Updated: Sep 21, 2022

Bitcoin is the father of blockchain technology. With Bitcoin started a new era of blockchain and decentralization. Bitcoin enabled everyone to make the peer-to-peer transactions they enjoy...

Continue reading
How to access Ethereum Mempool
Published: Oct 15, 2020
Updated: Sep 15, 2022

On Ethereum, when a transaction is sent, before being added to a block, it resides in what is called a Mempool. To receive information about this transaction, the Mempool must be queried. This...

Continue reading
The Web3 Developer Stack
Published: Jul 3, 2021
Updated: Sep 15, 2022

A developer stack is a bag of technologies a developer possesses. For example, MEAN (MongoDB, Express.js, AngularJS/Angular, and Node.js) and MERN (MongoDB, Express.js, React, and Node.js) are...

Continue reading
Introduction to Scaffold-ETH 🏗
Published: Oct 7, 2021
Updated: Sep 9, 2022

Developing applications involves juggling several moving pieces like front-ends, back-ends, and databases. But developing a decentralized application on a blockchain adds a few more elements...

Continue reading
How to create your own DAO with Aragon
Published: Aug 8, 2021
Updated: Sep 9, 2022

Blockchain provides us with the power of decentralization. Decentralization means the transfer of power to users/members rather than having a single centralized authority governing everything;...

Continue reading
How to connect to Ethereum using PHP
Published: Jun 11, 2021
Updated: Sep 9, 2022

PHP is a very popular choice among developers and has a vast community due to its long presence in web development. In this guide, we’ll cover how to connect to Ethereum with PHP using the

Continue reading
How to use Subspace with QuickNode
Published: Sep 8, 2020
Updated: Sep 9, 2022

In this guide, we'll understand a bit about reactive development and how to use Subspace with QuickNode.JavaScript is the programming language behind most of the internet apps and...

Continue reading