chain_subscribeNewHeads notifies you whenever a new block header is produced.
The node answers your request with a subscription ID, then pushes a chain_newHead notification for each new block. Each notification carries the block header: parent hash, block number, state root,
extrinsics root, and digest logs.
The subscription lasts as long as the WebSocket connection. Unsubscribe with chain_unsubscribeNewHeads before closing it.
Prerequisites
- A WebSocket endpoint for a peaq node. The script reads it from the
PEAQ_WS_URLenvironment variable. - Node.js, with the
wsanddotenvpackages. The example uses the rawwsclient so you see the exact JSON-RPC messages the node sends, without a Web3 library’s wrapping.
Instructions
1. Setting Up the Environment
- Install Dependencies: Ensure you install the necessary Node.js packages:
- Set ESM Module:
Add the following to your
package.jsonto allow for ESM modules.
- Environment Variables:
Create a
.envfile in your project directory (if not already present) and set the WebSocket endpoint URL:
2. The subscription flow
The script opens a WebSocket to the peaq node and sends achain_subscribeNewHeads request with no parameters. The node replies with a subscription ID, which the script stores.
Every later message the node pushes uses the method chain_newHead and carries a params object. The script compares params.subscription against the stored ID, then reads the header from params.result.
On SIGINT (Ctrl+C) the script sends chain_unsubscribeNewHeads with the subscription ID and closes the connection.
3. Running the Boilerplate
Subscribed to new heads with ID: <subscriptionId> confirms the subscription. Each header then prints under New Block Header received:.


