# Ethereum eth_chainId RPC method

Ethereum API method that returns the current chain ID. Chain ID is used to sign replay-protected transactions and generally verify if a network is the desired one. It was introduced in EIP-155 (opens new window).


  • none


  • quantity — EIP-155 Chain ID.

# Example:

  • web3.js
  • ethers.js
  • web3.py
  • eth.rb
  • cURL
const Web3 = require("web3");
const node_url = "CHAINSTACK_NODE_URL";
const web3 = new Web3(node_url);

web3.eth.getChainId((err, chain) => {

# Use case

One of the possible use cases for the chain_id method in Ethereum is to determine which chain a user is connected to when using a DApp with the MetaMask browser extension. This can be useful to provide a customized user experience based on the specific chain that the user is interacting with.

Here is an example of how the chain_id method might be used in this context with MetaMask. Note that the chain ID is returned as a hexadecimal value:

// Check which network is selected on MetaMask
async function checkChain() {

    // Declare the desired chain ID to match
    const desiredChainId = '0x1'; // Ethereum mainnet chain ID

    // Retrieve the current Chain ID selected by the user
        method: 'eth_chainId'
    }).then(chainId => {

        // compare the actual chain ID it to the declared chain ID
        if (chainId !== desiredChainId) {
            console.log(`You are currently on the wrong network. Please switch to the mainnet.`);

            // call the promtSwitch function
        } else {
            console.log("This is the correct network")

// Prompt user to switch to a determined network based on the chain ID
async function promtSwitch() {

    await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{
            chainId: '0x1' // chainId must be in HEX with 0x in front

In this case, the checkChain function is called to get the current chain ID using the Ethereum object provided by MetaMask. The chain ID is then checked to determine if the user is connected to the Ethereum mainnet and call the promtSwitch function to prompt the user to switch network in case the chain ID does not match the desiredChainId constant.