Web3.js Frontend Integration
Web3.js is the oldest JavaScript library for working with Ethereum. Version 4.x was released in 2024 with a redesigned API and TypeScript-first approach. If a project is starting from scratch, consider ethers.js v6 or viem as alternatives — they're lighter and have more predictable APIs. But Web3.js still dominates legacy projects and is a mandatory requirement for some clients.
Initialization and Provider Connection
import Web3 from 'web3';
// Via MetaMask / EIP-1193 provider
const web3 = new Web3(window.ethereum);
// Request access to accounts
const accounts = await web3.eth.requestAccounts();
const userAddress = accounts[0];
// Via HTTP RPC (for read-only operations)
const web3ReadOnly = new Web3('https://mainnet.infura.io/v3/YOUR_KEY');
In Web3.js v4, web3.eth.requestAccounts() replaces the old ethereum.enable(), which was deprecated in 2020 but still appears in copied examples.
Working with Contracts
Main pattern — instantiate contract via ABI and address:
import { AbiItem } from 'web3-utils';
import MyContractABI from './abi/MyContract.json';
const contract = new web3.eth.Contract(
MyContractABI as AbiItem[],
'0xContractAddress'
);
// Reading (call — free, doesn't require signature)
const value = await contract.methods.getValue().call();
// Writing (send — transaction, requires gas and signature)
const receipt = await contract.methods
.setValue(42)
.send({ from: userAddress });
Typical mistake — calling .send() without from. Web3.js either throws an exception or tries to guess the sender and returns unpredictable result.
Event Handling and Subscriptions
Web3.js supports event subscriptions via WebSocket provider:
const web3ws = new Web3('wss://mainnet.infura.io/ws/v3/YOUR_KEY');
contract.events.Transfer({ fromBlock: 'latest' })
.on('data', (event) => {
console.log(event.returnValues);
})
.on('error', (error) => {
// Must handle — WebSocket connection can break
});
HTTP provider doesn't support subscriptions — common reason "why my events don't work". For polling-based fallback use getPastEvents with interval.
Migration from v1/v2 to v4
If you maintain an old project: in v4 callbacks are removed in favor of promises everywhere, import changed (import Web3 from 'web3' instead of const Web3 = require('web3')), and utility methods moved to separate packages (web3-utils). Direct dependency replacement without fixes will break the project.







