{"id":16273,"library":"web3-providers-http","title":"Web3.js HTTP Provider","description":"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.","status":"active","version":"4.2.0","language":"javascript","source_language":"en","source_url":"https://github.com/ChainSafe/web3.js","tags":["javascript","typescript"],"install":[{"cmd":"npm install web3-providers-http","lang":"bash","label":"npm"},{"cmd":"yarn add web3-providers-http","lang":"bash","label":"yarn"},{"cmd":"pnpm add web3-providers-http","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package provides a provider for the main Web3.js library and is typically used in conjunction with it.","package":"web3","optional":false}],"imports":[{"note":"HttpProvider is a named export, not a default export.","wrong":"import HttpProvider from 'web3-providers-http';","symbol":"HttpProvider","correct":"import { HttpProvider } from 'web3-providers-http';"},{"note":"Since Web3.js v4, the `Web3` class is a named export. CommonJS `require('web3')` for the main Web3 object now also requires destructuring: `const { Web3 } = require('web3');`.","wrong":"const Web3 = require('web3');","symbol":"Web3","correct":"import { Web3 } from 'web3';"},{"note":"Importing types uses `import type` for better tree-shaking and clarity in TypeScript.","symbol":"HttpProviderOptions","correct":"import type { HttpProviderOptions } from 'web3-providers-http';"}],"quickstart":{"code":"import { Web3 } from 'web3';\nimport { HttpProvider } from 'web3-providers-http';\n\nasync function connectAndGetBlockNumber() {\n  const INFURA_API_KEY = process.env.INFURA_API_KEY ?? ''; // Use environment variable for API key\n  if (!INFURA_API_KEY) {\n    console.error('INFURA_API_KEY is not set. Please set it in your environment variables.');\n    process.exit(1);\n  }\n\n  const providerUrl = `https://mainnet.infura.io/v3/${INFURA_API_KEY}`;\n\n  try {\n    const httpProvider = new HttpProvider(providerUrl, { \n      providerOptions: { \n        headers: { 'User-Agent': 'MyWeb3App/1.0' }, \n        // Optionally set a timeout for requests\n        // timeout: 5000 \n      }\n    });\n    const web3 = new Web3(httpProvider);\n\n    const networkId = await web3.eth.net.getId();\n    console.log(`Connected to network ID: ${networkId}`);\n\n    const blockNumber = await web3.eth.getBlockNumber();\n    console.log(`Current block number: ${blockNumber}`);\n\n    // Example: Fetch account balance (requires an account address)\n    // const accountAddress = '0x...'; // Replace with a valid Ethereum address\n    // const balance = await web3.eth.getBalance(accountAddress);\n    // console.log(`Balance of ${accountAddress}: ${web3.utils.fromWei(balance, 'ether')} ETH`);\n\n  } catch (error: any) {\n    console.error('Failed to connect or retrieve data:', error.message || error);\n    // Detailed error logging for common issues\n    if (error.message.includes('CONNECTION ERROR')) {\n      console.error('Possible causes: Invalid URL, network firewall, or RPC node is down.');\n    } else if (error.message.includes('Invalid JSON RPC response')) {\n      console.error('Possible causes: Backend RPC issue, incorrect API key, or proxy problem.');\n    }\n  }\n}\n\nconnectAndGetBlockNumber();","lang":"typescript","description":"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."},"warnings":[{"fix":"Review the official Web3.js v1.x to v4.x migration guide. Update `import` statements, refactor callback-based code to use Promises, and adapt to native `BigInt` for numerical values.","message":"Web3.js v4 (and thus `web3-providers-http` v4) introduces significant breaking changes from v1.x. Most notably, the `Web3` class itself is now a named export (`import { Web3 } from 'web3'`) rather than a default export. Callbacks for most functions are no longer supported, with an emphasis on Promises and async/await.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Refactor code to handle `BigInt` values correctly. Convert to `number` or `string` using `Number()` or `String()` for display or specific operations, being mindful of potential precision loss for very large numbers. Use `web3.utils.toBN` if `BigNumber` functionality is still desired, though direct `BigInt` use is recommended.","message":"In Web3.js v4, numerical values from RPC calls (e.g., `getBalance`, `getBlockNumber`) are now returned as native `BigInt` instead of strings or `BigNumber` objects. This change requires updating any arithmetic or comparison logic.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"For real-time event subscriptions, use `web3-providers-ws` (`WebSocketProvider`) or an injected provider (like MetaMask) that supports event listening.","message":"HTTP providers do not support real-time event subscriptions or persistent connections, unlike WebSocket providers. Attempts to subscribe to events using an `HttpProvider` will fail or not yield expected results.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Always configure `HttpProvider` with an `https://` URL. Implement robust error handling for rate limit errors and consider using a service with higher rate limits or running your own node for heavy usage.","message":"When connecting to an HTTP/HTTPS RPC endpoint, especially with public services like Infura or Alchemy, it's crucial to use HTTPS to prevent man-in-the-middle attacks and protect sensitive data. Additionally, be aware of rate limits imposed by public endpoints.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Ensure your RPC node is configured to allow requests from your dApp's origin by setting `rpccorsdomain` (e.g., `geth --rpccorsdomain \"*\"` for development, or specific origins in production). For browser environments, an injected provider like MetaMask is often preferred to bypass direct CORS issues.","message":"Cross-Origin Resource Sharing (CORS) issues commonly arise when a dApp running in a browser tries to connect to an RPC node on a different origin. The browser might block the request if the RPC node's server doesn't send appropriate CORS headers.","severity":"gotcha","affected_versions":">=4.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"For ES Modules: `import { HttpProvider } from 'web3-providers-http';` and `import { Web3 } from 'web3';`. For CommonJS: `const { HttpProvider } = require('web3-providers-http');` and `const { Web3 } = require('web3');`.","cause":"`HttpProvider` is a named export from `web3-providers-http`, and `Web3` itself is a named export from `web3` in v4. Older code patterns or incorrect import syntax cause this error.","error":"TypeError: Web3.providers.HttpProvider is not a constructor"},{"fix":"Verify the RPC endpoint URL is correct and accessible. Check if the blockchain node is running and configured correctly. Ensure no firewalls are blocking the connection. If using a hosted service, confirm your API key is valid and not rate-limited.","cause":"The `HttpProvider` failed to establish a connection to the specified RPC endpoint. This can be due to an incorrect URL, the node being offline, network firewall restrictions, or an invalid API key (for hosted services).","error":"Error: CONNECTION ERROR: Couldn't connect to node ..."},{"fix":"Inspect the full error message for clues about the invalid response. Double-check the RPC endpoint URL, API key, and the format of your RPC requests. This often points to an issue on the backend service or misconfiguration.","cause":"The connected endpoint sent a response that was not a valid JSON-RPC format, indicating an issue with the RPC server, a proxy, or an incorrect API request.","error":"Error: Invalid JSON RPC response: \"...\""}],"ecosystem":"npm"}