In this article, we will learn how to use web3js to automatically handle blockchain disconnection in a production environment. The method described below applies to web3js version 1.0.0-beta.35, but also to the stable version 1.2 *.

How to use web3js to handle blockchain disconnection or restart

Problem description

If your team uses web3js in production, you must realize that there is no built-in reconnection feature in web3js to handle blockchain disconnection or restart. Therefore, in general, when the connection drops, the nodejs service needs to be restarted to connect to the blockchain again. This is not a very practical method.


Let’s see how we gracefully handle the broken block chain in nodejs. In the web3js library, the program provides us with the following events

Connect – connect

Error – program error

End — end of program connection.

After disconnection, we can use the termination event to restart a new web3js connection. Let’s take a look at an example to understand this:

File connection.js

In this file, we will deal with the connection between nodejs and blockchain. We will have a new block chain connection, which will return a Web3 active connection object.

const web3 = require(“web3”);

let hasProviderEnded = false, web3Instance, reconnecTInterval = 10000;

async funcTIon newBlockchainConnecTIon(webSocketProvider, endCallback) {

// create new provider

const provider = new web3. providers.WebsocketProvider (webSocketProvider);

hasProviderEnded = false;

// connect event fires when the connecTIon established successfully.

provider.on (‘connect’, () =》 console.log (“connected to blockchain”));

// error event fires whenever there is an error response from blockchain and this event also has an error object and message property of error gives us the specific reason for the error

provider.on (‘error’, (err) =》 console.log ( err.message ));

// end event fires whenever the connection end is detected. So Whenever this event fires we will try to reconnect to blockchain

provider.on (‘end’, async (err) =》 {

// handle multiple event calls sent by Web3JS library

if (hasProviderEnded) return;

// setting hashProviderEnded to true as sometimes the end event is fired multiple times by the provider

hasProviderEnded = true;

// reset the current provider

provider.reset ();

// removing all the listeners of provider.

provider.removeAllListeners (“connect”);

provider.removeAllListeners (“error”);

provider.removeAllListeners (“end”);

setTimeout(() =》 {

// emitting the restart event after some time to allow blockchain to complete startup

// we are listening to this event in the other file and this callback will initialize a new connection


}, reconnectInterval);


if (web3Instance == undefined) web3Instance = new web3(provider);

else web3 Instance.setProvider (provider);

return web3Instance;


module.exports = {



File app.js

const connection = require(“connection”);

const web3JSConnection;

const endCallback = async function () {

web3JSConnection = await connection.newBlockchainConnection (‘ws://’, customEvent);


async function getWeb3Connection() {

if (web3JSConnection == undefined) web3JSConnection = await connection.newBlockchainConnection (‘ws://’, endCallback);

return web3JSConnection;


module.exports = {




When the blockchain is disconnected, when the provider triggers a “terminate” event, we will trigger a callback after a timeout. The event then in turn calls the function to create a new blockchain connection.

The following points should be noted:

·Sometimes web3js sends you multiple “terminate” events for the same connection point, so we have to check if we have handled a disconnect event.

·Use “setprovider” to set a new provider in the Web3 instance object instead of creating a new Web3 instance.

·Reset the provider and remove the active listener

·The time interval for reconnection must be at least 5 seconds, and blockchain restart takes about 5 seconds.

Editor in charge


Leave a Reply

Your email address will not be published. Required fields are marked *