Web3 Providers - How to connect to Ethereum network with Web3.js

Web3 Providers - How to connect to Ethereum network with Web3.js

Table of Contents

Libraries and frameworks greatly simplify and speed up the development process. When it comes to Ethereum development — it is very helpful to use Web3.js. 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.

In this tutorial, we will learn how to use Web3.js to connect to the Ethereum blockchain using HTTP. We will write code to get the last block number. The most interesting thing about this will be that our code will work for both the front-end (with a build system such as webpack) and the back-end (using NodeJS).

Preinstalled

  • NodeJS is installed on your system
  • Text editor
  • Terminal or command line

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

Get API Key WatchData

To create an API key, you need to do the following steps:On the Dashboard.watchdata.io tab, click Create API key.

Create API key
Choose Ethereum Mainnet

Your API key will be automatically created.

Copy API key
API key result

Once you have created the API key, copy it and combine it with the HTTP provider’s endpoint in this format:



https://ethereum.api.watchdata.io/node/jsonrpc?api_key=YOUR_API_KEY_HERE

For example:



https://ethereum.api.watchdata.io/node/jsonrpc?api_key=83ab245b-ae08-43a4-97db-85903d35652f

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:

Ethereum network block

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.

Join the column

Contribute to our blog as a writer or propose a fresh idea for an article!