Ethereum is one of the most widely used blockchain platforms for building decentralized applications, smart contracts, digital assets, and enterprise blockchain solutions. For developers who already understand blockchain fundamentals, learning Ethereum development opens the door to a different ecosystem of tools, programming languages, and application patterns.
When I started exploring Ethereum development, one of the first libraries worth understanding was Web3.js. It provides JavaScript and TypeScript APIs that allow applications to communicate with Ethereum nodes, retrieve blockchain data, and interact with smart contracts.
In this article, we’ll build our understanding step by step. We’ll connect to Ethereum, read blocks and account balances, interact with an ERC-20 token contract, and learn how these concepts fit into a real project.
By the end, you’ll have a working starter project that you can extend with your own blockchain application.
What Is Web3.js?
Web3.js is a JavaScript library for communicating with Ethereum and other EVM-compatible blockchains. It provides APIs for interacting with Ethereum’s JSON-RPC interface without requiring developers to construct every RPC request manually.
With Web3.js, you can:
- Read the latest block and historical blockchain data.
- Retrieve account balances and transaction details.
- Connect applications to Ethereum nodes.
- Read data from deployed smart contracts.
- Send transactions and execute smart-contract functions.
- Listen for smart-contract events.
- Build the blockchain integration layer for decentralized applications.
For example, imagine building an asset-tracking application. Your frontend might allow users to view ownership information, while your backend or blockchain integration service reads smart-contract data from Ethereum. Web3.js provides the interface for communicating with the blockchain.
A note about its lifecycle: Web3.js was sunset on March 4, 2025, and its GitHub repository is archived. This tutorial uses Web3.js because it remains relevant for learning its APIs and maintaining existing applications. If you’re starting a new production project, evaluate actively maintained alternatives such as ethers.js or viem as well.
Official documentation: https://docs.web3js.org/
Step 1 Set Up the Development Environment
Before writing code, we need Node.js and npm. Node.js allows us to execute JavaScript outside the browser, while npm manages project dependencies.
You can download Node.js from https://nodejs.org/.
Verify the installation:
node --version
npm --version
Next, create a new project:
mkdir web3js-ethereum-starter
cd web3js-ethereum-starter
npm init -y
npm pkg set type=module
npm install web3
The type=module setting enables native JavaScript ES module imports, which are supported by Web3.js v4.
Create a file named index.js for your first example.
At this point, the project is ready to communicate with an Ethereum node.
Step 2 Understand the Connection Between Web3.js and Ethereum
Before making our first request, let’s understand the components involved.
A typical interaction follows this path:
- A JavaScript application calls a Web3.js method.
- Web3.js sends an RPC request through a configured provider.
- An Ethereum node processes the request.
- The node returns blockchain data.
- Web3.js exposes the result to the application.
The provider can be a local Ethereum development node, a node you operate yourself, or a hosted RPC service.
For example, a hosted provider may give you an endpoint similar to this:
https://your-ethereum-provider.example/v1/YOUR_API_KEY
This is only an illustrative URL. You must replace it with a real endpoint from your chosen provider.
For our examples, we’ll store the endpoint in an environment variable named ETHEREUM_RPC_URL.
On Windows PowerShell:
$env:ETHEREUM_RPC_URL="YOUR_ETHEREUM_RPC_URL"
On macOS or Linux:
export ETHEREUM_RPC_URL="YOUR_ETHEREUM_RPC_URL"
Keeping configuration outside the source code makes it easier to switch networks and helps prevent credentials from being committed to a repository.
Step 3 Connect to Ethereum and Read the Latest Block
Let’s begin with a simple example. We’ll create a Web3 instance, connect to the configured Ethereum endpoint, and retrieve the latest block number.
Create index.js:
import { Web3 } from "web3";
const rpcUrl = process.env.ETHEREUM_RPC_URL;
if (!rpcUrl) {
throw new Error(
"ETHEREUM_RPC_URL is not configured."
);
}
const web3 = new Web3(rpcUrl);
const blockNumber =
await web3.eth.getBlockNumber();
console.log(
"Latest Ethereum block:",
blockNumber.toString()
);Run the application:
node index.js
If the endpoint is configured correctly, the program prints the latest block number available from that node.
Let’s understand the important lines.
import { Web3 } from "web3" imports the Web3.js class.
new Web3(rpcUrl) initializes Web3.js with the RPC endpoint.
web3.eth.getBlockNumber() makes a read request to retrieve the latest block number.
We convert the result to a string because Web3.js v4 uses JavaScript BigInt for certain integer values. Converting it explicitly also makes the output easier to read.
This first example demonstrates a fundamental principle: an application can read public Ethereum blockchain data without owning a wallet or paying transaction gas fees.
Step 4 Retrieve More Information About a Block
A block number is useful, but developers often need additional information, such as the block hash and the number of transactions included in the block.
Let’s extend our example.
Create read-block.js:
import { Web3 } from "web3";
const rpcUrl = process.env.ETHEREUM_RPC_URL;
if (!rpcUrl) {
throw new Error(
"ETHEREUM_RPC_URL is not configured."
);
}
const web3 = new Web3(rpcUrl);
const chainId = await web3.eth.getChainId();
const blockNumber =
await web3.eth.getBlockNumber();
const block =
await web3.eth.getBlock(blockNumber);
console.log("Chain ID:", chainId.toString());
console.log(
"Block Number:",
blockNumber.toString()
);
console.log("Block Hash:", block.hash);
console.log(
"Transaction Count:",
block.transactions.length
);Execute it:
node read-block.js
The output will contain the network’s chain ID, latest block number, block hash, and transaction count.
For Ethereum mainnet, the chain ID is 1. A local development network or testnet will use a different chain ID.
Why is this useful?
A blockchain explorer, monitoring dashboard, or transaction analytics application needs to retrieve this kind of information regularly. Understanding these basic RPC operations gives us a foundation for building those applications.
Step 5 Read an Ethereum Account Balance
The next step is retrieving the ETH balance of an account.
In Ethereum, an account’s balance is represented in wei, the smallest denomination of ETH. One ETH equals 10¹⁸ wei.
Create read-balance.js:
import { Web3 } from "web3";
const rpcUrl = process.env.ETHEREUM_RPC_URL;
const address = process.env.ETHEREUM_ADDRESS;
if (!rpcUrl || !address) {
throw new Error(
"Configure ETHEREUM_RPC_URL and ETHEREUM_ADDRESS."
);
}
const web3 = new Web3(rpcUrl);
const balanceWei =
await web3.eth.getBalance(address);
const balanceEth =
web3.utils.fromWei(
balanceWei,
"ether"
);
console.log("Address:", address);
console.log(
"Balance in wei:",
balanceWei.toString()
);
console.log(
"Balance in ETH:",
balanceEth
);Set the account address separately.
Windows PowerShell:
$env:ETHEREUM_ADDRESS="0xYOUR_PUBLIC_ADDRESS"
node read-balance.js
macOS or Linux:
export ETHEREUM_ADDRESS="0xYOUR_PUBLIC_ADDRESS"
node read-balance.js
Replace the placeholder with a valid public Ethereum address.
The getBalance() method retrieves the balance in wei, while fromWei() converts it into ETH for display.
Notice that we don’t need a private key to retrieve a balance. Blockchain state is publicly readable, although some RPC providers may require an API key or enforce usage limits.
This is an important distinction between reading blockchain data and submitting a transaction.
Step 6 Interact With a Smart Contract Using Web3.js
So far, we’ve interacted directly with Ethereum’s blockchain data. In real applications, we frequently need to communicate with smart contracts.
Smart contracts contain business logic that executes on the Ethereum Virtual Machine (EVM). Examples include token contracts, voting systems, asset registries, supply-chain applications, and decentralized exchanges.
To interact with a contract, Web3.js needs two important pieces of information:
Contract address: The deployed contract’s address on the target network.
ABI: The Application Binary Interface, which describes the contract’s externally accessible functions, inputs, outputs, and events.
The ABI allows Web3.js to encode function calls and decode their results.
Example Read an ERC-20 Token Contract
Let’s read information from the Uniswap UNI token contract deployed on Ethereum mainnet.
The contract address is:
0x1f9840a85d5af5bf1d1762f925bdaddc4201f984
Create read-token.js:
import { Web3 } from "web3";
const rpcUrl = process.env.ETHEREUM_RPC_URL;
if (!rpcUrl) {
throw new Error(
"ETHEREUM_RPC_URL is not configured."
);
}
const web3 = new Web3(rpcUrl);
const tokenAddress =
"0x1f9840a85d5af5bf1d1762f925bdaddc4201f984";
const tokenAbi = [
{
inputs: [],
name: "name",
outputs: [
{ type: "string", name: "" }
],
stateMutability: "view",
type: "function"
},
{
inputs: [],
name: "symbol",
outputs: [
{ type: "string", name: "" }
],
stateMutability: "view",
type: "function"
},
{
inputs: [],
name: "decimals",
outputs: [
{ type: "uint8", name: "" }
],
stateMutability: "view",
type: "function"
},
{
inputs: [],
name: "totalSupply",
outputs: [
{ type: "uint256", name: "" }
],
stateMutability: "view",
type: "function"
}
];
const token = new web3.eth.Contract(
tokenAbi,
tokenAddress
);
const name =
await token.methods.name().call();
const symbol =
await token.methods.symbol().call();
const decimals =
await token.methods.decimals().call();
const totalSupply =
await token.methods.totalSupply().call();
console.log("Token Name:", name);
console.log("Token Symbol:", symbol);
console.log("Decimals:", decimals.toString());
console.log(
"Raw Total Supply:",
totalSupply.toString()
);Run the example:
node read-token.js
The output includes the token’s name, symbol, decimals, and raw total supply.
The total supply returned by the contract is an integer expressed in the token’s smallest units. To display a human-readable token amount, divide the raw supply by 10 raised to the number of decimals. For precise financial calculations, use a decimal-safe arithmetic library rather than JavaScript floating-point arithmetic.
What Happens Behind the Scenes?
When we create the contract instance, Web3.js associates the ABI with the deployed contract address.
When we call:
await token.methods.symbol().call();Web3.js encodes the symbol() function call, sends it to the node, and decodes the returned value.
The .call() method executes a read-only contract call. It doesn’t create a transaction that changes the blockchain’s state, so it doesn’t require a funded account to pay gas.
This pattern is useful when developing token dashboards, blockchain explorers, asset-tracking systems, and applications that display smart-contract data.
Step 7 Build and Deploy Your Own Smart Contract
Reading an existing contract is a good starting point. The next step is to create a contract of your own.
For this example, we’ll build a simple message board that stores a message on the blockchain.
Create a file named MessageBoard.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract MessageBoard {
string private message;
event MessageUpdated(
address indexed updatedBy,
string newMessage
);
constructor() {
message = "Hello Ethereum";
}
function getMessage()
external
view
returns (string memory)
{
return message;
}
function setMessage(
string calldata newMessage
) external {
message = newMessage;
emit MessageUpdated(
msg.sender,
newMessage
);
}
}This contract has three important components.
The constructor initializes the message when the contract is deployed.
The getMessage() function reads the current message without changing blockchain state.
The setMessage() function updates the stored message and emits an event. Calling this function through a transaction changes the blockchain state and requires gas.
Deploy the Contract
For a beginner-friendly approach, you can compile and deploy this contract using the Remix IDE:
Create the Solidity file in Remix, compile it with a compatible Solidity compiler, and deploy it to a local development environment or a supported testnet.
After deployment, record the contract address and the compiled ABI.
For a real project, keep the ABI in a separate JSON file generated by your build process rather than manually maintaining it.
Never deploy experimental code to mainnet without appropriate testing and security review.
Step 8 Read and Update Your Contract With Web3.js
Once your contract is deployed, create a JavaScript file that loads its address and ABI.
For this example, save the ABI generated by Remix as MessageBoard.abi.json and place it in your project.
Create message-board.js:
import { Web3 } from "web3";
import { readFile } from "node:fs/promises";
const rpcUrl = process.env.ETHEREUM_RPC_URL;
const contractAddress =
process.env.MESSAGE_BOARD_ADDRESS;
if (!rpcUrl || !contractAddress) {
throw new Error(
"Configure the RPC URL and contract address."
);
}
const web3 = new Web3(rpcUrl);
const abi = JSON.parse(
await readFile(
new URL("./MessageBoard.abi.json", import.meta.url),
"utf8"
)
);
const contract = new web3.eth.Contract(
abi,
contractAddress
);
// Read the stored message
const message =
await contract.methods.getMessage().call();
console.log("Current message:", message);This demonstrates how a JavaScript application reads state from a contract you control.
What About Updating the Message?
Updating the message requires a transaction, not a read-only call.
For a browser-based application, a common pattern is to connect to a wallet such as MetaMask and ask the user to approve the transaction. The wallet signs the transaction and submits it to the selected network.
For a backend service, transactions can be signed using a securely managed account or signing service. The private key must never be hardcoded in the source code or exposed to browser clients.
The general Web3.js pattern for a write operation is:
const receipt = await contract.methods
.setMessage("Learning Ethereum with Web3.js")
.send({
from: senderAddress
});
console.log(
"Transaction hash:",
receipt.transactionHash
);This is an illustrative call pattern, not a complete wallet setup. It assumes that a suitable signing mechanism and transaction sender are configured. On a browser, the application must connect to the user’s wallet and handle its account and network permissions. In a backend, the application must securely sign the transaction.
Use a local development network or testnet for your first write transactions.
Step 9 Understand Events and Transaction Receipts
Smart contracts often emit events to make important state changes easier to observe.
In our MessageBoard contract, the following event is emitted whenever the message changes:
event MessageUpdated(
address indexed updatedBy,
string newMessage
);Applications can query or subscribe to these events to track changes without repeatedly reading every contract field.
For example, after a write transaction, the transaction receipt can help you determine whether execution succeeded and retrieve information about the transaction.
console.log("Transaction hash:", receipt.transactionHash);
console.log("Transaction status:", receipt.status);Web3.js also supports contract event APIs. For historical event retrieval, use the appropriate contract event-query methods. For live subscriptions, use a WebSocket-capable provider and verify that the selected node supports the required subscription methods.
This is particularly useful for notification systems, transaction monitoring, asset transfers, and event-driven enterprise applications.
Step 10 Organize the Project for Real Development
As the project grows, avoid putting all blockchain logic in one file.
A more maintainable structure could look like this:
web3js-ethereum-starter/
├── src/
│ ├── config/
│ │ └── ethereum.js
│ ├── services/
│ │ ├── block-service.js
│ │ ├── account-service.js
│ │ └── contract-service.js
│ ├── contracts/
│ │ └── MessageBoard.abi.json
│ └── index.js
├── contracts/
│ └── MessageBoard.sol
├── test/
├── package.json
└── .gitignoreThe configuration module can create the Web3 instance. Service modules can encapsulate blockchain operations, while contract ABIs and Solidity source code remain organized separately.
For more complex applications, use a development environment such as Hardhat to compile, test, deploy, and debug smart contracts. See https://hardhat.org/docs/getting-started.
This separation makes the code easier to test and helps prevent blockchain-specific logic from spreading throughout the application.
Common Mistakes to Avoid
Confusing wei with ETH: Ethereum balances are returned in wei. Convert them before displaying the value to users.
Using the wrong network: A contract address on Ethereum mainnet may not point to the same contract on a testnet or local network.
Using an incorrect ABI: The ABI must match the contract interface you intend to call.
Exposing private keys: Never commit private keys, recovery phrases, or provider credentials to source control.
Treating a transaction submission as a successful state change: Check the transaction receipt and execution status before reporting success.
Ignoring library lifecycle: Web3.js is sunset. For new production systems, evaluate actively maintained alternatives and their security and compatibility characteristics.
Conclusion
Getting started with Web3.js is easier when you approach it one operation at a time. Begin by connecting to Ethereum and reading blocks, then retrieve account balances and inspect transactions. Once those concepts are clear, move on to smart-contract interaction, transaction signing, and event monitoring.
The examples in this article provide the foundation for a small Ethereum integration project. You can extend them into a token dashboard, asset registry, blockchain explorer, or enterprise application. The most important next step is to build something practical. Create a small contract, deploy it locally, connect to it from JavaScript, and experiment with both read and write operations. That experience will help you understand how Ethereum’s smart-contract ecosystem works in real applications.
