Learn how to subscribe to real-time blockchain events using WebSocket — new blocks, logs, pending transactions, and token transfers with KuberNodes.
HTTP polling wastes requests and adds latency. WebSocket subscriptions push events to your app the instant they happen — new blocks in ~12s on Ethereum, ~2s on Polygon, sub-second on L2s.
The most common subscription. Get notified of every new block with its number, hash, timestamp, and transaction count.
import { createPublicClient, webSocket } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: webSocket('wss://ws.kubernodes.com/ethereum?apiKey=YOUR_KEY'),
})
client.watchBlockNumber({
onBlockNumber: (n) => console.log('Block:', n),
})Filter for specific events from a contract address. Perfect for monitoring ERC-20 transfers, NFT mints, or DEX swaps.
import { parseAbiItem } from 'viem'
// Watch for USDC Transfer events
client.watchEvent({
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
event: parseAbiItem('event Transfer(address from, address to, uint256 value)'),
onLogs: (logs) => {
for (const log of logs) {
console.log(`${log.args.from} → ${log.args.to}: ${log.args.value}`)
}
},
})Monitor the mempool for unconfirmed transactions. Useful for MEV, front-running protection, and transaction monitoring.
// Raw eth_subscribe for pending transactions
const ws = new WebSocket('wss://ws.kubernodes.com/ethereum?apiKey=YOUR_KEY')
ws.onopen = () => {
ws.send(JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'eth_subscribe',
params: ['newPendingTransactions'],
}))
}
ws.onmessage = (event) => {
const data = JSON.parse(event.data)
if (data.params) {
console.log('Pending tx:', data.params.result)
}
}WebSocket connections can drop. Always implement reconnection logic and heartbeat monitoring for production applications.
// Production-grade reconnection with viem
import { createPublicClient, webSocket, fallback, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: fallback([
webSocket('wss://ws.kubernodes.com/ethereum?apiKey=YOUR_KEY', {
reconnect: { attempts: 10, delay: 1000 },
}),
http('https://rpc.kubernodes.com/ethereum?apiKey=YOUR_KEY'), // fallback
]),
})Get a free API key and start making requests in under 5 minutes.
Create free account