Web3.js HTTP Provider

4.2.0 · active · verified Tue Apr 21

The `web3-providers-http` package provides the essential HTTP connectivity layer for the Web3.js library, enabling decentralized applications (dApps) to interact with Ethereum or any EVM-compatible blockchain node via standard HTTP/HTTPS JSON-RPC requests. It is a fundamental component for querying blockchain data, sending transactions, and interacting with smart contracts when persistent connections like WebSockets are not required or available. While the specific npm metadata indicates version `4.2.0`, the broader Web3.js monorepo, which this package is part of, is under active development with recent releases up to `4.16.0`. Web3.js maintains a rapid release cadence, frequently delivering minor and patch updates across its modular packages. Key differentiators for Web3.js v4 include a complete rewrite in TypeScript for enhanced type safety, full ESM and CJS module support, a focus on tree-shaking for optimized bundle sizes, and the use of native BigInt for numerical operations, moving away from external BigNumber libraries. It integrates deeply into the Web3.js ecosystem, providing robust error handling and broad compatibility with various Ethereum client implementations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate and use `web3-providers-http` with the `Web3` object to connect to an Ethereum node (e.g., Infura), retrieve the network ID, and fetch the latest block number, including basic error handling.

import { Web3 } from 'web3';
import { HttpProvider } from 'web3-providers-http';

async function connectAndGetBlockNumber() {
  const INFURA_API_KEY = process.env.INFURA_API_KEY ?? ''; // Use environment variable for API key
  if (!INFURA_API_KEY) {
    console.error('INFURA_API_KEY is not set. Please set it in your environment variables.');
    process.exit(1);
  }

  const providerUrl = `https://mainnet.infura.io/v3/${INFURA_API_KEY}`;

  try {
    const httpProvider = new HttpProvider(providerUrl, { 
      providerOptions: { 
        headers: { 'User-Agent': 'MyWeb3App/1.0' }, 
        // Optionally set a timeout for requests
        // timeout: 5000 
      }
    });
    const web3 = new Web3(httpProvider);

    const networkId = await web3.eth.net.getId();
    console.log(`Connected to network ID: ${networkId}`);

    const blockNumber = await web3.eth.getBlockNumber();
    console.log(`Current block number: ${blockNumber}`);

    // Example: Fetch account balance (requires an account address)
    // const accountAddress = '0x...'; // Replace with a valid Ethereum address
    // const balance = await web3.eth.getBalance(accountAddress);
    // console.log(`Balance of ${accountAddress}: ${web3.utils.fromWei(balance, 'ether')} ETH`);

  } catch (error: any) {
    console.error('Failed to connect or retrieve data:', error.message || error);
    // Detailed error logging for common issues
    if (error.message.includes('CONNECTION ERROR')) {
      console.error('Possible causes: Invalid URL, network firewall, or RPC node is down.');
    } else if (error.message.includes('Invalid JSON RPC response')) {
      console.error('Possible causes: Backend RPC issue, incorrect API key, or proxy problem.');
    }
  }
}

connectAndGetBlockNumber();

view raw JSON →