How to detect when the connected wallet changes selected network web3 JS

In this tutorial, we are going to learn how to detect when the wallet connected to your website selects a new network with Web3 JS

In this tutorial, we are going to learn how to detect when the wallet connected to your website selects a new network with Web3 JS.

This is useful for 2 reasons:

  1. it allows you to always know what network the user selected so you don't fire transactions in the wrong network (which might fail)
  2. it allows you to update your UI according to the selected network
  3. it allows you ask the user to select the right network

Now, the first thing you need to do is install the Web3 library:

npm install web3

For this tutorial, we are going to connect a MetaMask wallet to the website. For that, we are going to use this code:

if (window.ethereum) {
    const accounts = await window.ethereum.request({method: 'eth_requestAccounts'});

    const account = accounts[0]
    const web3 = new Web3(window.ethereum);
    
    const currentNetworkId = await web3.eth.getChainId();
}

That code will open a MetaMask screen asking the user to accept connecting his wallet to your website.

If the user accepts, we store the connected account in a variable called account and we instantiate a Web3 object using window.ethereum (meaning the MetaMask wallet).

Then, we get the current selected network with web3.eth.getChainId and we store it in currentNetworkId.

To know which blockchain corresponds to which id, you can have a look at the full list of EVM chain IDs here: https://chainlist.org/

After that, we can run code when the selected wallet changes using this code:

web3.currentProvider.on('chainChanged', (newChainId) => {
    // Do something here with newChainId
});

An example of code you can run when the chain changes, is to ask the user to select a new network. We have a tutorial on how to request a network change on MetaMask (basically display a MetaMask pop-up asking the user to switch network)

And that's it! 👏

Thanks for reading this article!