How to Connect to the Ethereum Network using Node and Web3

Connect Node to Ethereum tutorial banner

Connecting to the Ethereum network is the first step of any blockchain project in Node.js. Your code never talks to the chain directly. It talks to an Ethereum node over JSON-RPC, and Web3.js is the library that handles that conversation for you.

This tutorial shows you how to set up a node endpoint, connect to it with Web3.js, and read live data from the network.

If you want to go deeper on how the chain itself works before connecting any code, the introduction to blockchain covers the fundamentals.

How an Ethereum connection works

An Ethereum node is a program that stores the chain and answers requests through the JSON-RPC protocol over HTTPS. When your code asks for the latest block number, it sends a JSON payload like eth_blockNumber to the node’s URL and gets a JSON response back.

Running your own node means syncing hundreds of gigabytes of chain data, so most applications connect to a hosted node provider or a free public RPC endpoint instead. You only need a URL, and both options below give you one in minutes.

What you need

  • Node.js installed locally. The examples here run on the current stable release.
  • An Ethereum endpoint URL from Infura or a public RPC (both covered below).
  • The Web3.js library, added with npm.

Get an Ethereum node endpoint

You have two practical ways to get an endpoint URL. Pick one now and swap it later if you outgrow it.

Option 1: Infura

Infura is a hosted blockchain API service from Consensys. Create a free account, create a new API key, and choose the network you want. Each key gives you URLs shaped like this:

https://mainnet.infura.io/v3/YOUR_API_KEY
https://sepolia.infura.io/v3/YOUR_API_KEY

Mainnet is where ether has actual market value. Sepolia is the current testnet for development, and either works for reading data while you follow along.

For a full walkthrough of the Infura setup, see our guide to configuring Infura with Web3 and Node.js.

Note that older tutorials point at Ropsten or Rinkeby. The Ethereum Foundation decommissioned those testnets between 2022 and 2023, and their endpoints no longer work. Use Sepolia when you need a test network.

Option 2: A free public RPC endpoint

If you want to run code before creating any account, community-operated public nodes expose open endpoints. One reliable example is:

https://ethereum-sepolia-rpc.publicnode.com

Public endpoints rate-limit anonymous traffic and offer no uptime guarantee, which makes them fine for learning and prototypes but a poor foundation for production. Once your app matters, move to Infura or another managed provider where you can monitor usage and get support.

Connect to Ethereum from Node.js

Create a new folder, initialize a project, and install Web3.js. At the time of writing, the current release is web3 4.x, which changed the import compared to the older 1.x line: the Web3 class is now a named export.

npm init -y
npm install web3

The connection code

Create a file named app.js. The script builds a Web3 instance around the endpoint URL, then makes two read calls: one for the chain ID, which identifies exactly which network you reached, and one for the latest block number.

const { Web3 } = require("web3");

// Any Ethereum JSON-RPC endpoint works. This one is a free public Sepolia node.
const rpcUrl = "https://ethereum-sepolia-rpc.publicnode.com";

async function main() {
  const web3 = new Web3(rpcUrl);

  const chainId = await web3.eth.getChainId();
  const blockNumber = await web3.eth.getBlockNumber();

  console.log("Connected. Chain ID:", chainId.toString());
  console.log("Latest block number:", blockNumber.toString());
}

main().catch((e) => {
  console.error("Connection failed:", e.message);
  process.exit(1);
});

Passing the URL string directly to the Web3 constructor is the modern style in web3 4.x. The old form, new Web3(new Web3.providers.HttpProvider(url)), still works when you need provider-specific options.

Both getChainId() and getBlockNumber() return BigInt values, which is why the code prints them with toString(). Interpolating a BigInt into some output paths throws a TypeError, so make the conversion explicit.

Run it:

node app.js

Here is the actual output from running this exact script against the Sepolia endpoint:

Output of node app.js showing chain ID 11155111 and the latest Sepolia block number

What the output tells you

Chain ID 11155111 confirms the connection landed on Sepolia. Mainnet would report 1.

The block number climbs every few seconds because Sepolia produces blocks continuously, so your number will be higher than the one shown here. That moving value proves you are reading live chain state over the internet, not cached data.

When the connection fails

The most common failure is a bad endpoint URL or an invalid API key. With an Infura URL containing a wrong key, the request reaches the server but Infura rejects it, and Web3.js surfaces the error as a fetch failure. Running the earlier script against a deliberately invalid Infura key prints:

Connection failed: invalid json response body at https://mainnet.infura.io/v3/YOUR_API_KEY reason: Unexpected token 'i', "invalid project id
" is not valid JSON

The phrase invalid project id is Infura telling you the key was rejected. Check that the key from the Infura dashboard is pasted completely, with no stray spaces, and that the network name in the URL matches a key network you actually enabled.

If the error instead mentions DNS resolution or a timeout, the endpoint URL itself is wrong or unreachable. Test it directly with curl before blaming your code:

curl -X POST -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
  https://ethereum-sepolia-rpc.publicnode.com

A healthy endpoint answers with a result field containing the block height in hex.

Where to go next

Reading data costs nothing and needs no account. Sending transactions is the natural next step, and it needs a funded account. Our guide on sending Ethereum with Node and Web3 walks through that flow end to end.

Pankaj Kumar
Pankaj Kumar

Pankaj Kumar is the founder and CEO of CodeForGeek, with more than 14 years in IT. He is an open-source enthusiast who enjoys sharing what he learns through CodeForGeek and YouTube, with a focus on Python, data analytics, machine learning, Angular, Node.js, and Kafka.

Articles: 335