8

How to check the current MetaMask network?

For example, if the current network is Rinkeby, I need the string "rinkeby".

3 Answers 3

13

You can check the current network chain ID like this:

console.log(window.ethereum.networkVersion, 'window.ethereum.networkVersion');

And these are the chain IDs for the most used ethereum networks:

  1. Mainnet: 1
  2. Kovan: 42
  3. Ropsten: 3
  4. Rinkeby: 4
  5. Goerli: 5
6
  • 1
    typeof window.ethereum.networkVersion is string. Commented Sep 29, 2021 at 16:07
  • 1
    I never said it's not a string, it's the network ID represented as string. Commented Sep 29, 2021 at 20:17
  • 😄 😄 yeah, I just added it to avoid confusion. Commented Sep 30, 2021 at 10:38
  • 1
    Is there a place I can find all chain ids ? Lets say if I want to know the chain id of matic main chain, where should I check. Sorry if this is a dumb question. Newbie here ! Commented Nov 19, 2021 at 13:05
  • @TheEhsanSarshar very important note, thank you! Because when you listen to the chainChanged event it returns a number.
    – ihor.eth
    Commented Dec 24, 2021 at 5:48
2

@vishnusatis check this website to find all chain ids. https://chainlist.org/

1

For those looking for an up-to-date answer (April 2024):

You should be using chain ids rather than network ids. More on that on this post by Pedro Gomes (WalletConnect's founder).

To get the chain id with web3.js 4.x, you should use web3.eth.getChainId() instead, and map that to the network name yourself:

const SUPPORTED_CHAINS_NAMES: Record<number, string> = {
  1: 'Ethereum  Mainnet',
  11155111: 'Sepolia',
};

const chainId = Number(await web3.eth.getChainId());
const chainName = SUPPORTED_CHAINS_NAMES[chainId] || 'Unsupported Chain';

Or use a library like eth-chains to get up-to-date chain information, instead of manually mapping the chain id:

const chainId = Number(await web3.eth.getChainId());
const chainInfo = chains.getById(chainId) || null;
const chainName = chainInfo?.name || 'Unsupported Chain';

window.ethereum.chainId, window.ethereum.networkVersion, window.ethereum.selectedAddress are legacy / deprecated provider properties that will eventually be removed. See https://github.com/MetaMask/metamask-improvement-proposals/discussions/23.

Also, see web3.js' migration guide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.