Web3.js

Web3.js overview

Web3.js is the official library from the Ethereum Foundation. It is a great way to develop a website/client application that interacts with the JSON RPC of the Ethereum blockchain.

Adding web3.js

First you need to get web3.js into your project. This can be done using the following methods:

  • npm: npm install web3

  • yarn: yarn add web3

  • pure js: link the dist/web3.min.js

Connecting through Web3

Now let’s create a short script, let’s call it `index.js` to get the last block number from the blockchain. You can copy/paste this into your code editor:

const Web3 = require('web3');
const provider = new Web3.providers.HttpProvider('YOUR_ETHEREUM_NODE_URL');
const web3 = new Web3(provider);
web3.eth.getBlockNumber().then((result) => {
	console.log("Latest Ethereum Block is ", result);
});

So go ahead and replace `YOUR_ETHEREUM_NODE_URL` with the http provider from the instructions above.

A brief explanation of the above code: we import the web3 library we installed earlier (line 1), set the URL of our Ethereum host (line 2), create a Web3 HttpProvider instance (line 3) . Finally, we call getBlockNumber for the web3 object and wait for a successful result from the server and then write the result to the console (lines 4–6).

Save this piece of code to an index.js file, which we will run shortly. Run the file with the node command, and you will see the last block number from the Ethereum network:

And so we connected to web3 and got the last block number. Great :) You can use Web3.js and WatchData API to develop great applications.

Last updated