I'm looking to get the ID of the chain/network I'm running a script on in hardhat. How can I get the names and IDs?

2 Answers 2


There are a few ways to get the network/chain name/id. We are going to assume you are in a script that you'd like to run, or a test. When running these, you must have a hardhat.config.ts or hardhat.config.js, and you must be running the script "in" hardhat. For example: npx hardhat run scripts/your_script_here.ts

import hre from 'hardhat'
const networkName = hre.network.name
const chainId = hre.network.config.chainId

This means, you'll need a hardhat.config that looks something like:

const config: HardhatUserConfig = {
    defaultNetwork: 'hardhat',
    networks: {
        hardhat: {
            chainId: 31337,
            accounts: [process.env.PRIVATE_KEY!],

You could also create a file that has a mapping between your network/chain name and ID.

Alternatively, you could use hardhat-deploy with something like:

import { HardhatRuntimeEnvironment } from 'hardhat/types'
import { DeployFunction } from 'hardhat-deploy/types'
const deployScript: DeployFunction = async function (
  hre: HardhatRuntimeEnvironment
) {
  const { getChainId } = hre
  const chainId = await getChainId()

Combined with a network mapping.

  • Hi, big fan thanks for ur videos :) could you please do a video or tutorial or blog article to explain the new gas system in ethereum and how to configure it correctly inside a transaction in hardhat or ethers. It was very simple before London fork.. now it is not :(
    – Majd TL
    Nov 5, 2021 at 18:10

Another way to do it that works for me is

const { ethers } = require("hardhat");

const network = await ethers.getDefaultProvider().getNetwork();
console.log("Network name=", network.name);
console.log("Network chain id=", network.chainId);

As with the accepted answer, you must be running "in" Hardhat for this to work.

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.