Skip to main content
The peaq network exposes a JSON-RPC interface over WebSockets that lets clients subscribe to chain events. 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_URL environment variable.
  • Node.js, with the ws and dotenv packages. The example uses the raw ws client 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.json to allow for ESM modules.
  • Environment Variables: Create a .env file 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 a chain_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

Run the script with Node.js:
Subscribed to new heads with ID: <subscriptionId> confirms the subscription. Each header then prints under New Block Header received:. eth-subscribe-new-heads-1 Press Ctrl+C to unsubscribe and close the connection.