Using web3js it is possible get network ID using the following method:

// Contract ABI Load
const ABISimpleStorage = require("./build/contracts/SimpleStorage.json");

// Besu Connection Web3 Load
let web3 = new Web3(
  new Web3.providers.WebsocketProvider("ws://")
    const netID = await web3.eth.net.getId();

How we could do same thing in ethers.js?

const ABISimpleStorage = require("./build/contracts/SimpleStorage.json");
let provider = new ethers.providers.JsonRpcProvider();

let contract = new ethers.Contract(



This worked for me:

const { chainId } = await provider.getNetwork()
console.log(chainId) // 42

Use the provider.getNetwork() function. It will return a Network type and in it contain the chainId. You can see in the doc here: https://docs.ethers.io/ethers.js/html/api-providers.html#id2

UPDATE: as it turn out i was wrong the chainID and networkID are the same most of the time, not all of the time and there aren’t any api in etherjs so you need to use json-rpc instead. To do that you use this: https://docs.ethers.io/v5/api/providers/jsonrpc-provider/#JsonRpcProvider-send. Where the method is “net_version” and the params is an empty array. It will return like this: https://eth.wiki/json-rpc/API#net_version.

  • Really thanks I've to read
    – brunillopu
    Apr 11 '20 at 18:45
  • Unfortunately, in ethers.js version 5, the chain id returned in provider.getNetwork() differs from the network id. Or in other words, in ethers.js version 4, the network id was returned instead of the chain id. So this does not work anymore. Jul 5 '20 at 13:12
  • @ Marc Wäckerlin chainId and networkId are the same but with different name that's all: ethereum.stackexchange.com/a/37536/50595
    – haxerl
    Jul 7 '20 at 1:46
  • 3
    chainId and networkId are not the same.
    – tuler
    Jul 10 '20 at 19:31

I was searching this today.

Try provider.getNetwork().chainId.

getNetwork().name gives human readable name like 'homestead'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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