Configure Infura with Web3.js and Node.js

An Infura HTTPS endpoint gives your Node.js program an Ethereum JSON-RPC connection without operating an Ethereum node, and Web3.js can confirm it by reading a chain ID and block number.

What Infura and Web3.js each do

Infura supplies an HTTPS JSON-RPC endpoint for an Ethereum network, where JSON-RPC is the request format used for calls such as eth_chainId and eth_blockNumber.

Web3.js is the JavaScript client library that sends JSON-RPC requests through the endpoint and converts the responses into JavaScript values.

Keep the endpoint out of your source file

Your Infura endpoint contains an API key, so do not commit it to a repository. Pass it through an environment variable locally, then use your deployment platform’s secret settings in production.

Create the Node.js project

Use an empty directory so the dependency and the connection file stay together. The commands install the Web3.js package from npm.

mkdir infura-connect
cd infura-connect
npm init -y
npm install web3

Create an Infura project in its dashboard and copy the HTTPS endpoint for the Ethereum network you intend to query. Use a network name and API key from that project in the environment variable below.

export INFURA_RPC_URL="https://<network>.infura.io/v3/<your-api-key>"

Connect Web3.js to the Infura endpoint

Save this file as connect-infura.mjs. The Web3 constructor receives the HTTPS endpoint, then the script requests the network chain ID and latest block number.

import { Web3 } from "web3";

const rpcUrl = process.env.INFURA_RPC_URL;

if (!rpcUrl) {
  throw new Error("Set INFURA_RPC_URL to an Infura HTTPS endpoint before running this file.");
}

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

console.log(`Connected to chain ID ${chainId}`);
console.log(`Latest block number ${blockNumber}`);

Run the file after setting INFURA_RPC_URL. A successful response confirms that the endpoint accepts JSON-RPC requests and that Web3.js can decode the result.

node connect-infura.mjs
Terminal output showing Web3.js connected to Ethereum chain ID 1 and returning a block number
Web3.js connects through an HTTPS JSON-RPC endpoint and reads the chain ID and block number.

The executed file received chain ID 1 plus a block number from a publicly reachable Ethereum endpoint. Replace that endpoint with your Infura endpoint before using the script for your application.

Read the output

Chain ID 1 identifies Ethereum mainnet. The block number changes as new blocks are added, so use it as a connection check rather than a fixed expected value.

If the request fails

An unset variable raises the explicit error from the script. A 401 or 403 response usually means the API key, project policy, network endpoint, or request limit needs attention in the Infura project settings.

If Web3.js reports an invalid JSON-RPC response, check that the URL is an HTTPS RPC endpoint rather than a dashboard or documentation URL. The Ethereum JSON-RPC specification lists the methods that an endpoint can expose.

Choose HTTP or WebSocket for the job

An HTTPS endpoint suits request and response work such as reading balances, blocks, and contract state. Use a WebSocket endpoint when your application must subscribe to events or newly produced blocks.

Web3.js documents HTTP, WebSocket, and IPC provider options. Select the transport from the behavior your program needs instead of switching providers after a subscription call fails.

Next step

After the connection check passes, request a block with web3.eth.getBlock or read a contract with its ABI and address. Keep write operations separate until you have chosen how your application will sign transactions.

For implementation details, read the Web3.js provider guide, the Web3.js eth guide, and Ethereum.org’s JSON-RPC API reference.

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