> ## Documentation Index
> Fetch the complete documentation index at: https://docs.peaq.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# chain_subscribeNewHeads

The peaq network exposes a **JSON-RPC interface** over WebSockets that allows clients to **subscribe** to various chain events. In this guide, we focus on the `chain_subscribeNewHeads` method.
It is designed to notify you whenever a new **block header** is produced on the blockchain. When you call this method, the node returns a subscription ID. Subsequently, as new
blocks are finalized or produced, the node pushes notifications to your client containing block header information (such as the **parent hash**, **block number**, **state root**, **extrinsics root**, and **digest logs**).

Key points:

* `chain_subscribeNewHeads` is a stable and well-supported JSON-RPC method for **header subscriptions**.
* Once subscribed, the node sends notifications (commonly using the method `"chain_newHead"` or sometimes `"subscription"`) that include the block header data.
* The subscription is maintained over the lifetime of the WebSocket connection. To clean up, you should unsubscribe using `chain_unsubscribeNewHeads` before closing the connection.

## Prerequisites

Before proceeding, the following Prerequisites are made:

1. **WebSocket Endpoint:**
   * You have access to a peaq node via a WebSocket endpoint. The script expects this endpoint to be available via an environment variable (e.g., `PEAQ_WS_URL`). If not provided, it falls back to a default endpoint (e.g., `wss://quicknode.peaq.xyz`).

2. **JSON‑RPC Support:**
   * The node supports the standard JSON-RPC methods, including **`chain_subscribeNewHeads`** and **`chain_unsubscribeNewHeads`**. This guide assumes you are using the stable methods (rather than unstable alternatives that may not work reliably).

3. **Raw WebSocket Library (ws):**
   * To avoid any interference from additional wrappers (such as those found in some Web3 libraries), the example uses the `ws` package. This ensures that you receive the exact JSON-RPC messages directly from the node.

4. **Chain Activity:**
   * The network is producing new blocks. If no new blocks are produced after you subscribe, you may not see any notifications immediately.

## Instructions

### 1. Setting Up the Environment

* **Install Dependencies:**
  Ensure you install the necessary Node.js packages:

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
npm install ws dotenv
```

* **Set ESM Module:**
  Add the following to your `package.json` to alllow for ESM modules.

```javascript theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
"type": "module",
```

* **Environment Variables:**
  Create a `.env` file in your project directory (if not already present) and set the WebSocket endpoint URL:

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
PEAQ_WS_URL=wss://quicknode.peaq.xyz
```

### 2. Understanding the Subscription Flow

* **Initiating the Connection:**
  The script establishes a direct WebSocket connection to the peaq node. Once connected, it sends a JSON-RPC payload to subscribe to new block headers using the **`chain_subscribeNewHeads`** method.

* **Subscription Request:**
  The JSON‑RPC request payload includes:
  * `"jsonrpc": "2.0"`: The protocol version.
  * `"method": "chain_subscribeNewHeads"`: The method to subscribe to block headers.
  * `"params": []`: No additional parameters are required.
  * `"id": 1`: A unique identifier for the request.

* **Handling the Response:**
  The node responds with a JSON-RPC message that includes a subscription ID. This ID is saved locally and used to filter incoming notifications.

* **Receiving Notifications:**
  After a successful subscription, the node pushes notifications (using either `"chain_newHead"` or the generic `"subscription"` method) that include a `params` object. The script checks if the incoming message's `subscription` field matches the stored subscription ID and then parses out the block header details.

* **Graceful Shutdown:**
  When the client (or user) sends an interrupt (SIGINT, usually via Ctrl+C), the script sends an unsubscribe request using **`chain_unsubscribeNewHeads`** with the subscription ID. This cleanly ends the subscription and then closes the WebSocket connection.

### 3. Running the Boilerplate

<CodeGroup>
  ```javascript JavaScript theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
  // chain_subscribeNewHeads.js

  import dotenv from 'dotenv';
  dotenv.config();

  import WebSocket from 'ws';

  const WS_URL = process.env.PEAQ_WS_URL;
  const ws = new WebSocket(WS_URL);

  let subscriptionId = null;
  const SUBSCRIBE_REQUEST_ID = 1;
  const UNSUBSCRIBE_REQUEST_ID = 2;

  ws.on('open', () => {
    console.log("WebSocket connected");

    // Send a subscription request using the stable method "chain_subscribeNewHeads"
    const subscribePayload = {
      jsonrpc: "2.0",
      method: "chain_subscribeNewHeads",
      params: [],
      id: SUBSCRIBE_REQUEST_ID,
    };

    console.log("Sending subscription payload:", JSON.stringify(subscribePayload));
    ws.send(JSON.stringify(subscribePayload));
  });

  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message);
      console.log("Received message:", JSON.stringify(data, null, 2));

      // Handle the subscription response (id: 1)
      if (data.id === SUBSCRIBE_REQUEST_ID && data.result) {
        subscriptionId = data.result;
        console.log("Subscribed to new heads with ID:", subscriptionId);
      }
      // Handle incoming notifications for new block headers
      // Some nodes may return notifications under the method "chain_newHead" or the generic "subscription"
      else if ((data.method === 'chain_newHead' || data.method === 'subscription') &&
               data.params &&
               data.params.subscription === subscriptionId) {
        console.log("New Block Header received:");
        console.log(data.params.result);
      }
    } catch (e) {
      console.error("Error parsing message:", message);
    }
  });

  ws.on('error', (error) => {
    console.error("WebSocket error:", error);
  });

  ws.on('close', () => {
    console.log("WebSocket connection closed");
  });

  // Graceful shutdown: send an unsubscribe request and close the socket
  process.on('SIGINT', () => {
    console.log("\nGracefully shutting down...");
    if (subscriptionId) {
      const unsubscribePayload = {
        jsonrpc: "2.0",
        method: "chain_unsubscribeNewHeads",
        params: [subscriptionId],
        id: UNSUBSCRIBE_REQUEST_ID,
      };
      console.log("Sending unsubscribe payload:", JSON.stringify(unsubscribePayload));
      ws.send(JSON.stringify(unsubscribePayload), () => {
        ws.close();
        process.exit();
      });
    } else {
      ws.close();
      process.exit();
    }
  });

  console.log("Listening for new block headers on the peaq network (chain_subscribeNewHeads) using ws...");
  ```
</CodeGroup>

* **Start the Script:**
  Run the script using Node.js:

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
node chain_subscribeNewHeads.js
```

* You should see logs indicating that the WebSocket connection is established and that the subscription request has been sent. If new blocks are produced, you will see the raw notifications logged (including block header details).
  <img src="https://mintcdn.com/peaq/bfUMfJGiNN2sOYvn/assets/img/eth-subscribe-new-heads-1.png?fit=max&auto=format&n=bfUMfJGiNN2sOYvn&q=85&s=a8b51af35ea82c474c6693e0a749b51e" alt="eth-subscribe-new-heads-1" width="1265" height="1231" data-path="assets/img/eth-subscribe-new-heads-1.png" />

* **Interpreting Logs:**
  * A log entry like `Subscribed to new heads with ID: <subscriptionId>` confirms the subscription was successful.
  * When a new block header is received, the script prints the details under the message `New Block Header received:`.
  * If no notifications are received, double-check that the chain is active and that the node is emitting new block headers.

* **Shutdown:** Press Ctrl+C to trigger the graceful shutdown. The script will send an unsubscribe request before closing the connection.

## Summary

This guide walked you through the process of listening and parsing chain events (block headers) on the peaq network using the **`chain_subscribeNewHeads`** JSON-RPC method.

Using this approach, you can reliably monitor **new block headers** on the peaq network and integrate these events into your blockchain applications or debugging workflows.
