> ## 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

> Subscribe to new peaq block headers using chain_subscribeNewHeads over WebSockets. Parse chain_newHead notifications and unsubscribe when finished.

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:

```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 allow 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://quicknode1.peaq.xyz
```

### 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

```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
    else if (data.method === 'chain_newHead' &&
             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...");
```

Run the script with Node.js:

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
node chain_subscribeNewHeads.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](https://mintcdn.com/peaq/bfUMfJGiNN2sOYvn/assets/img/eth-subscribe-new-heads-1.png?fit=max\&auto=format\&n=bfUMfJGiNN2sOYvn\&q=85\&s=a8b51af35ea82c474c6693e0a749b51e)

Press Ctrl+C to unsubscribe and close the connection.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.