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

# subscribe ("newBlockHeaders") | Avalanche

> Reference docs for the subscribe ("newBlockHeaders") JSON-RPC method on the Avalanche blockchain, available via Chainstack JSON-RPC nodes.

The ethers.js subscription equivalent to [eth\_newBlockFilter](/reference/avalanche-newblockfilter). `subscribe("newBlockHeaders")` allows developers to subscribe to real-time updates about new block headers on the Avalanche blockchain; the application will receive notifications whenever a new block is added to the blockchain. The notification will include information about the new block, such as its block number, hash, and timestamp.

## Parameters

* `string` — a keyword identifying the type of event to subscribe to, `newBlockHeaders` in this case.
* `function` — (optional) a callback function that will be called every time a new event of the specified type is received. This function takes two parameters: `error` and `result`. The error parameter contains any error that occurred while subscribing to the event, and the result parameter contains the data for the event that was received.

## Response

* `object`— a block object with the following fields:

  * `number` — the block number of the requested block, encoded as hexadecimal. `null` if the block is pending.
  * `hash` — the block hash of the requested block. `null` if the block pending.
  * `parenthash` — hash of the previous block used to generate the current block. Also known as the 'parent block'.
  * `nonce` — the hash used to demonstrate proof-of-work. `null` if the block pending. It returns `0x0000000000000000` when the consensus is proof-of-stake.
  * `sha3uncles` — the hash of the list of uncles included in the block. It is used to identify the block uniquely and to verify the integrity of the block's data.
  * `logsbloom` — the bloom filter for the logs of the block, a data structure that allows for efficient membership testing of elements in a set, in this case, the logs included in the block. `null` if pending.
  * `transactionsroot` — the root of the transaction trie of the block. The `transactionsRoot` field allows Avalanche nodes to verify the integrity of the transactions in a block.
  * `stateroot` — the root of the final state trie of the block. The `stateroot` field is included in the block header and is used to verify the integrity of the state at the time the block was processed
  * `receiptsroot` — the root of the receipts trie of the block. A 32-byte hash of the root node of the receipts trie of all transactions in the block. It is used to verify the integrity of the receipts data for all transactions in the block.
  * `miner` — the address of the miner receiving the reward.
  * `difficulty` — a measure of how hard it is to find a valid block for the Avalanche blockchain. It is a number that increases as more miners join the network and more blocks are added to the chain, encoded as hexadecimal.
  * `totaldifficulty` — the cumulative sum of the difficulty of all blocks that have been mined in the Avalanche network since the inception of the network. It measures the overall security and integrity of the Avalanche network.
  * `extradata` — extra data included in a block by the miner who mined it. It often includes messages or other information related to the block.
  * `size` — the size of this block in bytes as an integer value, encoded as hexadecimal.
  * `gaslimit` — the maximum gas allowed in this block, encoded as hexadecimal.
  * `gasused` — the total used gas by all transactions in this block, encoded as hexadecimal.
  * `timestamp` — the Unix timestamp for when the block was collated.
  * `transactions` — an array of transaction objects. See [eth\_getTransactionByHash](/reference/ethereum-gettransactionbyhash) for the exact shape.
  * `uncles` — an array of uncle hashes.

## `subscribe("newBlockHeaders")` code example

<Info>
  Note that ethers.js subscriptions require a WebSocket connection.
</Info>

Use the [provider event listeners](https://docs.ethers.org/v6/api/providers/#Provider-on) to react to subscription events on the `WebSocketProvider`:

* `provider.on("block", listener)` — activates for each new block header received.
* `provider.on("error", listener)` — activates if an error is detected during the subscription.
* `provider.off("block", listener)` — removes the listener and stops the subscription.
* `provider.destroy()` — closes the WebSocket connection.

<CodeGroup>
  ```javascript index.js theme={"system"}
  const { ethers } = require("ethers");
  const NODE_URL = "CHAINSTACK_WSS_URL";
  const provider = new ethers.WebSocketProvider(NODE_URL);

  async function subscribeToNewBlocks() {
      try {
          // Subscribe to the 'block' event for new block headers
          provider.on("block", handleNewBlock);

          // React to any provider errors during the subscription
          provider.on("error", handleError);

          console.log("New subscription to block headers");
      } catch (error) {
          console.error(`Error subscribing to new blocks: ${error}`);
      }
  }

  /* Fallback functions to react to the different events */

  // Event listener that fetches and logs the received block header data
  async function handleNewBlock(blockNumber) {
      const blockHeader = await provider.getBlock(blockNumber);
      console.log(blockHeader);
  }

  // Event listener that logs any errors that occur
  function handleError(error) {
      console.error(`Error receiving new blocks: ${error}`);
  }

  subscribeToNewBlocks();
  ```
</CodeGroup>

## Use case

A practical use case for `subscribe("newBlockHeaders")` is a DApp that continuously listens for new block headers, then isolates the block number and `baseFeePerGas` for analytics purposes.

The following is an implementation of this concept using ethers.js subscriptions:

<CodeGroup>
  ```javascript index.js theme={"system"}
  const { ethers } = require("ethers");
  const NODE_URL = "CHAINSTACK_WSS_URL";
  const provider = new ethers.WebSocketProvider(NODE_URL);

  let blockCount = 0;

  async function subscribeToNewBlocks() {
      try {
          // Subscribe to the 'block' event for new block headers
          provider.on("block", handleNewBlock);

          // React to any provider errors during the subscription
          provider.on("error", handleError);

          console.log("New subscription to block headers");
      } catch (error) {
          console.error(`Error subscribing to new blocks: ${error}`);
      }
  }

  function unsubscribeFromNewBlocks() {
      // Remove the listener and close the WebSocket connection
      provider.off("block", handleNewBlock);
      provider.destroy();
      console.log("Successfully unsubscribed!");
      return process.exit(1);
  }

  /* Fallback functions to react to the different events */

  // Event listener that extracts block number and base fee per gas from the received block header data
  async function handleNewBlock(blockNumber) {

      const blockHeader = await provider.getBlock(blockNumber);
      const baseFeePerGas = blockHeader.baseFeePerGas;
      const baseFeeGwei = ethers.formatUnits(baseFeePerGas, "gwei");

      blockCount++;
      console.log(`Block number: ${blockNumber} \n Base Fee per Gas: ${baseFeeGwei} Gwei \n`);
      if (blockCount === 100) {
          unsubscribeFromNewBlocks();
      }
  }

  // Event listener that logs any errors that occur
  function handleError(error) {
      console.error(`Error receiving new blocks: ${error}`);
  }

  subscribeToNewBlocks();
  ```
</CodeGroup>

This code creates a new subscription to new block headers using the `provider.on("block", listener)` method on a `WebSocketProvider`. This method registers a listener that is called with the block number every time a new block is added.

The code defines two event listener functions that are attached to the provider: `handleNewBlock` and `handleError`. The `handleNewBlock` function is called when a new block header is received, and it fetches the full block with `provider.getBlock` and then extracts the block number and base fee per gas from the block header data using the `ethers.formatUnits` method. The `handleError` function is called when an error occurs, and it logs an error message.

This code includes an `unsubscribeFromNewBlocks` function which removes the listener with `provider.off`, closes the WebSocket connection with `provider.destroy`, and quits the program using `return process.exit(1)` after it received 100 new blocks. This is to demonstrate its use.

Finally, the code calls the `subscribeToNewBlocks` function, which creates the subscription and attaches the event listeners. When a new block header is received, the `handleNewBlock` function is called to extract the block data and log it to the console.
