Web3 by Example: Subscribing to New Blocks

The EventEmitter API allows applications to use an Observer Pattern to register callbacks for when various events occur. We can use this to subscribe new blocks.

provider.on add a listener to be triggered for each event. We can subscribe "block" event that is emitted when a new block is mined.

subscribe.js

const { ethers } = require("ethers");
(async () => {
const provider = new ethers.providers.AlchemyProvider();
provider.on("block", async (blockNumber) => {
console.log(blockNumber);
});
})();

output

➜ node subscribe.js
14302419
14302420
14302421
14302422
14302423

Next example: Send Raw Transaction