How to switch network on a MetaMask wallet using web3

In this tutorial we are going to see how you can switch the network of the wallet that is connected on your web app using web3.

The first step to this tutorial is to install the web3 dependency if you haven't already:

npm install web3

Then you need to connect to the user's wallet using any method you want. You can check out our guides if you want to learn how to connect to a wallet.

Once it's done, you need to find the blockchain id of the blockchain you want to switch to. You can find this ID on this page: https://chainlist.org/

Before switching the network, you need to check if you are not already connected to the right network.

Here's how to check the wallet's current network using web3:

import Web3 from 'web3'

// create a web3 instance using a browser wallet or any another provider
const web3 = new Web3(window.ethereum)

const getNetworkId = async () => {
  const currentChainId = await web3.eth.net.getId()
  return currentChainId
}

We first create a web3 instance with the browser wallet (stored in window.ethereum) and then we use that instance to access the getId method under the eth and net properties.

Now that we have a function to get the current network ID, let's see how to switch network.

Let's say we are connected to the Ethereum network and want to switch to the Binance Smart Chain. If we look at the networks list I shared previously, we can see that the BSC chain ID is 56.

Here's how to switch to the BSC network (or any other network, just replace the chain ID):

const swichNetwork = async (chainId) => {

  const currentChainId = await getNetworkId()
  
  if (currentChainId !== chainId) {
    try {
      await web3.currentProvider.request({
        method: 'wallet_switchEthereumChain',
          params: [{ chainId: Web3.utils.toHex(chainId) }],
        });
    } catch (switchError) {
      // This error code indicates that the chain has not been added to MetaMask.
      if (switchError.code === 4902) {
        alert('add this chain id')
      }
    }
  }
}

switchNetwork(56)

Here we use web3.currentProvider.request and call the switchEthereumChain method after checking that we are not already connected to the right chain.

Of course you can handle the errors differently than what we did here, this is just a minimal example. We'll see on another tutorial how users can add a network to MetaMask through your dApp.

Thanks for reading this tutorial 🙂