# chain_subscribeNewHeads - Bittensor

> Example code for the chain_subscribeNewHeads JSON-RPC method. Complete guide on how to use chain_subscribeNewHeads JSON-RPC in GetBlock Web3 documentation.

Subscribes to new block headers as they are produced. Returns a subscription ID; matching headers arrive as separate WebSocket messages with method `chain_newHead`.

> **Info:** **Substrate native JSON-RPC method.** Call against a GetBlock endpoint configured for the Substrate interface. For typed SDK access, use [Polkadot.js](https://polkadot.js.org/docs/api) (TypeScript) or [substrateinterface](https://github.com/polkascan/py-substrate-interface) (Python).

> **Warning:** **WebSocket-only method.** This method requires the WebSocket transport at `wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/`. It will not work via HTTP POST.

## Parameters

* None

## Request Example

#### cURL

```bash
# WebSocket-only method. Use wscat (or similar) to connect first:
wscat -c 'wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/'

# Then send:
{"jsonrpc": "2.0", "method": "chain_subscribeNewHeads", "params": [], "id": "getblock.io"}
```

#### JavaScript (Axios)

```javascript
import WebSocket from 'ws';

const ws = new WebSocket('wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/');

ws.on('open', () => {
    ws.send(JSON.stringify({
    "jsonrpc": "2.0",
    "method": "chain_subscribeNewHeads",
    "params": [],
    "id": "getblock.io"
}));
});

ws.on('message', (data) => {
    console.log(JSON.parse(data.toString()));
});
```

#### Python (Requests)

```python
import asyncio
import json
import websockets

async def main():
    async with websockets.connect('wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/') as ws:
        await ws.send(json.dumps({
    "jsonrpc": "2.0",
    "method": "chain_subscribeNewHeads",
    "params": [],
    "id": "getblock.io"
}))
        async for message in ws:
            print(json.loads(message))

asyncio.run(main())
```

#### Rust (Reqwest)

```rust
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Message;
use serde_json::json;
use futures_util::{SinkExt, StreamExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (mut ws_stream, _) = connect_async("wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/").await?;

    let payload = json!({
        "jsonrpc": "2.0",
        "method": "chain_subscribeNewHeads",
        "params": [],
        "id": "getblock.io"
});
    ws_stream.send(Message::Text(payload.to_string())).await?;

    while let Some(msg) = ws_stream.next().await {
        println!("{:?}", msg?);
    }
    Ok(())
}
```

## Response Example

```json
{
    "jsonrpc": "2.0",
    "id": "getblock.io",
    "result": "9DZyB1n6BvF5dQ8wQRhgrxqCw"
}
```

## Response Parameters

| Field | Type | Description |
| --- | --- | --- |
| result | string | Subscription ID — match incoming `chain_newHead` notifications by this ID |

## Use Cases

* Real-time block notifications for indexers, explorers, and dashboards
* Triggering downstream processing on every new block
* Replacing inefficient polling with push-based delivery

## Error Handling

| Status Code | Error Message | Cause |
| --- | --- | --- |
| 403 | Forbidden | Missing or invalid `<ACCESS-TOKEN>` |
| -32602 | Invalid params | Request parameters are missing or malformed |
| -32601 | Method not found | Method does not exist on this interface — check whether you're calling a Substrate method on an EVM endpoint or vice versa |
| -32603 | Internal error | Server-side error while processing the request |
| 429 | Too Many Requests | Rate limit exceeded for your plan |

## SDK Integration

#### Polkadot.js (TypeScript)

```javascript
import { ApiPromise, WsProvider } from '@polkadot/api';

const provider = new WsProvider('wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/');
const api = await ApiPromise.create({ provider });

// Typed wrapper: api.rpc.chain.subscribeNewHeads(...)
const result = await api.rpc.chain.subscribeNewHeads();
console.log(result.toHuman());

// Or use the raw RPC interface for any method:
// const raw = await api.rpc.send({ method: 'chain_subscribeNewHeads', params: [] });
```

#### substrateinterface (Python)

```python
from substrateinterface import SubstrateInterface

substrate = SubstrateInterface(url="wss://shared.eu-central-1.getblock.io/<ACCESS-TOKEN>/")

# Generic RPC call:
result = substrate.rpc_request("chain_subscribeNewHeads", [])
print(result)
```
