How to Create javascript WebSockets Subscriptions to Ethereum and Binance Smart Chain through ethers.js? – Benzinga
Creating a WebSockets subscription to Ethereum and Binance Smart Chain using ethers.js can be useful for developers for several reasons, including scalability and easier integration.
Using NOWNodes to create WebSockets subscriptions to blockchain networks is a common practice. Javascript libraries such as ether.js have been a popular framework for WebSockets development.
Enter your email and you'll also get Benzinga's ultimate morning update AND a free $30 gift card and more!
WebSockets subscription is similar to an Event Listener in Javascript. There are several reasons why an Event Listener is essential. This article illustrates creating simple BSC WebSocket and Ethereum websocket subscriptions to popular Blockchain networks like Ethereum and Binance Smart Chain.
Why create a Javascript WebSockets subscription
Javascript WebSockets subscription is either the Ethereum blockchain or the Binance Smart Chain is important for several reasons. Below are some of the reasons to develop a WebSockets subscription.
WebSockets are communication protocols that enable real-time, two-way communication between a client (such as a web browser) and a server. It provides a persistent connection between the client and server, sending and receiving real-time data.
Constant communication is often established through Websockets API. The WebSockets API provides methods for opening and closing connections, sending and receiving data, and handling errors and events. WebSockets offer a powerful and flexible way to enable real-time communication between client-side and server-side applications. They have become essential for building modern web applications crucial for blockchain and web 3 development.
Platforms like NOWNodes provide more straightforward ways to establish such connections, making it much easier to alleviate the need for a technical developer team. Below is a step-by-step guide on importing the ethers.js library and developing WebSockets subscription to the Ethereum blockchain network and Binance Smart Chain.
How to import ethers.js library and create WebSockets subscription
To use the Ethers.js library, first of all, you need to learn how to install ethers. npm install ethers Then you can import it using the code below.
const { ethers } = require("ethers");
After importing, you create a provider instance directly connecting to the preferred blockchain network. In this case, either the Ethereum blockchain or the Binance Smart Chain. Below is the line of code to create the required connection using NOWnodes.
const provider = new ethers.providers.WebSocketProvider("'wss://bsc.nownodes.io/wss/YOUR_API_KEY');
It is important to note that you'll be required to replace YOUR_API_KEY with your actual NOWNodes API key in development.
Subsequently, create a contract instance using the below line of code.
const contractAddress = "0x..."; // The contract address you want to interact with
const abi = [...] // The ABI of the contract
const contract = new ethers.Contract(contractAddress, abi, provider);
Next, you should create a subscription to an event emitted by the contract. To do so, you'll need to implement the code line below.
contract.on("EventName", (arg1, arg2, event) => {
console.log("Event received:", arg1, arg2);
});
Important Notes:
Below is the code for WebSockets that connect to the Binance Smart Chain blockchain network using the NOWNodes node provider.
const { ethers } = require('ethers')
const url = 'wss://bsc.nownodes.io/wss/YOUR_API_KEY'
const EXPECTED_PONG_BACK = 15000
const KEEP_ALIVE_CHECK_INTERVAL = 7500
const startConnection = async () => {
const provider = new ethers.providers.WebSocketProvider(url, {
name: 'binance',
chainId: 56,
})
let pingTimeout = null
let keepAliveInterval = null
provider._websocket.on('open', () => {
console.log('Connect')
keepAliveInterval = setInterval(() => {
console.log('Checking if the connection is alive, sending a ping')
provider._websocket.ping()
// Use WebSocket#terminate(), which immediately destroys the connection,
// instead of WebSocket#close(), which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
pingTimeout = setTimeout(() => {
provider._websocket.terminate()
}, EXPECTED_PONG_BACK)
}, KEEP_ALIVE_CHECK_INTERVAL)
})
provider._websocket.on('close', () => {
console.error('The websocket connection was closed')
clearInterval(keepAliveInterval)
clearTimeout(pingTimeout)
startConnection()
})
provider._websocket.on('pong', () => {
console.log('Received pong, so connection is alive, clearing the timeout')
clearInterval(pingTimeout)
})
provider.on('block',(block)=>{
console.log('New block!', block)
})
}
startConnection()
Some advanced features of ethers.js for creating Ethereum/BSC WebSockets
Ethers.js provides a variety of advanced features for creating Ethereum WebSocket and BSC websocket subscriptions. Here are a few examples:
You can filter events based on specific parameters using the `ethers.utils` library. For example, to filter for a specific token transfer event, you could use the following code:
const filter = {
address: contractAddress,
topics: [ethers.utils.id('Transfer(address,address,uint256)')],
fromBlock: 'latest'
};
const logs = await provider.getLogs(filter);
If the WebSockets connection is lost, Ethers.js will automatically attempt to reconnect to the Ethereum node. You can also configure the number of reconnection attempts and the delay between attempts using the WebSocketProvider options.
For instance, to configure the WebSockets provider to retry every 5 seconds for up to 10 times, you could use the code below:
const options = {
reconnect: {
maxAttempts: 10,
delay: 5000
}
};
const provider = new ethers.providers.WebSocketProvider('wss://bsc.nownodes.io/wss/YOUR_API_KEY');
This code creates a reconnect object in the provider options that specifies the maximum number of attempts and the delay between attempts.
Using the provider, you can send multiple requests to an Ethereum node in a single batch.send() method. This can help reduce latency and improve performance. For instance, to retrieve the balances of multiple accounts in a single batch, you could use the following block of code:
const requests = [
{ method: 'eth_getBalance', params: ['0x123...', 'latest'] },
{ method: 'eth_getBalance', params: ['0x456...', 'latest'] },
{ method: 'eth_getBalance', params: ['0x789...', 'latest'] }
];
const results = await provider.send('eth_batch', requests);
What you get with NOWNodes service:
NOWNodes offers three paid plans, pro, business, and enterprise. It also provides a FREE plan suitable for small projects.
Start: FREE/ 100,000 requests per month + 1 API key and access to 5 nodes.
Pro: 20 / 1,000,000 requests per month + up to 3 API keys and access to all nodes Business: 200 / 30,000,000 requests per month + up to 25 API keys and access to all nodes.
Enterprise: 500 / 100,000,000 requests per month + up to 100 API keys and access to all nodes.
Conclusion
For several reasons, creating WebSockets with platforms such as NOWNodes can be important for maintaining high-security levels, constant uptime, and interoperability. Using the code snippet above, you can establish BSC WebSocket and Ethereum WebSocket using Ethers.js. The resulting WebSockets subscription would ensure Real-time communication, enhanced security, and scalability to ensure the growth of Web 3 projects.
Media Contact Company Name: NOWNodesEmail: Send EmailCountry: EstoniaWebsite: https://nownodes.io/
See the original post:
- Binance Taps Cyberscope as Exclusive Smart Contract Audit Partner for BNB Chain - The AI Journal - October 23rd, 2025 [October 23rd, 2025]
- New North Korean Malware OtterCookie Targets Ethereum and Binance Smart Chain Users - Analytics Insight - October 19th, 2025 [October 19th, 2025]
- 4AI Raises $6 Million to Build Decentralised AI Network on Binance Smart Chain - Ventureburn - October 15th, 2025 [October 15th, 2025]
- BNB Smart Chain Trading Competition: Trade AOP, STBL and BLESS to Share $2M Worth of Rewards - Binance - October 11th, 2025 [October 11th, 2025]
- Binance Smart Chain USDT Transaction Blowing Up, Here Are Triggers - Coinspeaker - October 9th, 2025 [October 9th, 2025]
- BNB Smart Chain Trading Competition: Trade PINGPONG and ASP to Share $2M Worth of Rewards - Binance - October 4th, 2025 [October 4th, 2025]
- Binance to Close MANTRA Deposits on Ethereum and BNB Smart Chain Networks - Happy Coin News - September 17th, 2025 [September 17th, 2025]
- Athene Network Migrates From Ethereum To Binance Smart Chain - BlockchainReporter - August 3rd, 2025 [August 3rd, 2025]
- BNB Smart Chain Trading Competition: Trade ASP, ZRC, YALA and TA to Share $3.2M Worth of Rewards - Binance - July 30th, 2025 [July 30th, 2025]
- $BOB Has Officially Moved to BNB Smart Chain (BSC)! - Binance - July 27th, 2025 [July 27th, 2025]
- What is DeFi & How Can You Use It Safely on Binance Smart Chain? - Binance - July 24th, 2025 [July 24th, 2025]
- Binance Halts Withdrawals for BNB Smart Chain and opBNB Chain Maintenance - AInvest - July 22nd, 2025 [July 22nd, 2025]
- BNB Smart Chain Trading Competition: Trade M, IDOL, AIN, CROSS and ECHO to Share $3M Worth of Rewards - Binance - July 16th, 2025 [July 16th, 2025]
- UXLINK Votes to Expand Ecosystem with Binance Smart Chain Migration - AInvest - July 8th, 2025 [July 8th, 2025]
- Deep Dive: The Future of $FUN on Binance Smart Chain - Binance - July 8th, 2025 [July 8th, 2025]
- Can Binance Smart Chain Sustain Its Roaring Comeback? - galaxy.com - July 2nd, 2025 [July 2nd, 2025]
- Binance Offers Zero-Fee Withdrawals for USD1 Stablecoin on BNB Smart Chain - tokenpost.com - May 28th, 2025 [May 28th, 2025]
- Binance Smart Chain eyes major fee reduction amid rising user activity - Mitrade - May 10th, 2025 [May 10th, 2025]
- Binance Plans To Suspend BNB Smart Chain Transactions On April 17 - TronWeekly - April 18th, 2025 [April 18th, 2025]
- Binance to suspend deposit and withdrawal for BNB Smart Chain temporarily on April 17 - Crypto News - April 18th, 2025 [April 18th, 2025]
- Binance Smart Chain-based Venus Protocol votes to 'reimburse' Venus Labs $1.7 million for work done in second half of 2024 - The Block - April 10th, 2025 [April 10th, 2025]
- Stablecoins Concentrated on Major Blockchains: Ethereum, Tron, Solana, and Binance Smart Chain - Blockchain News - April 5th, 2025 [April 5th, 2025]
- Stablecoins Predominantly Concentrated on Ethereum, Tron, Solana, and Binance Smart Chain - Blockchain.News - March 30th, 2025 [March 30th, 2025]
- OmegaX Health ($OmegaX) Expands to Binance Smart Chain The Future of AI Healthcare on Blockchain - GlobeNewswire - March 30th, 2025 [March 30th, 2025]
- Revival of Memecoin Trading on Binance Smart Chain - Blockchain.News - March 22nd, 2025 [March 22nd, 2025]
- Binance Will Support the BNB Smart Chain (BEP20) and opBNB Chain (opBNB) Network Upgrade & Hard Fork - 2025-03-20 | Binance announcement - Binance - March 22nd, 2025 [March 22nd, 2025]
- Breaking News: Cosmos ($ATOM) Enables Inter-Blockchain Communication; Connects with Ethereum ($ETH), Binance Smart Chain ($BSC), and Terra ($LUNA) -... - February 7th, 2025 [February 7th, 2025]
- Ethereum News: Ethereum (ETH)bPrice Targets $3.7K Amid Growing Smart Money Confidence and On-chain Strength - Binance - November 24th, 2024 [November 24th, 2024]
- Pattieswap/PattiePad Announces Last Stage Pre-sale of $PATTIE Token on Binance Smart Chain - GlobeNewswire - November 17th, 2024 [November 17th, 2024]
- A beginners guide to the BNB Chain: The evolution of the Binance Smart Chain - Cointelegraph - November 14th, 2024 [November 14th, 2024]
- BABY PEPE; Meet the Largest Pepe Token on the Binance Smart Chain Network! - Binance - October 12th, 2024 [October 12th, 2024]
- IAMDOG Expands to Binance Smart Chain: Bringing Meme Culture, Transparent Rewards, and an Engaging Gaming Experience to Millions - Benzinga - October 7th, 2024 [October 7th, 2024]
- Binance Smart Chain Expands with AI Deal, Why This is Great for FET and RCOF - Live Bitcoin News - September 6th, 2024 [September 6th, 2024]
- Binance to Temporarily Suspend Deposits and Withdrawals on BNB Smart Chain Soon: Heres Why - CryptoPotato - September 6th, 2024 [September 6th, 2024]
- Binance Integrates DeXe (DEXE) on BNB Smart Chain, Opens Deposits and Withdrawals - Blockchain.News - June 18th, 2024 [June 18th, 2024]
- DeFi Exchange 1Inch Expands to Binance Smart Chain Citing ETH Gas Fees - Yahoo News UK - June 18th, 2024 [June 18th, 2024]
- WUSD Stablecoin Expands Reach with Integration on Binance Smart Chain and Solana - PR Newswire - June 18th, 2024 [June 18th, 2024]
- Memereum Surpasses 21 Million Tokens Sold in Presale, Pioneers Blockchain-Based Insurance on Binance Smart ... - CryptoPotato - June 12th, 2024 [June 12th, 2024]
- Exploring the rise of Binance Coin: factors behind its surging value and future prospects - The National - The National - June 12th, 2024 [June 12th, 2024]
- Binance Coin (BNB) Surges Over 6%, Hits All-Time High Amid Network Growth - NullTX - June 12th, 2024 [June 12th, 2024]
- Tupan Launches the New Binance Smart Chain TCT - GlobeNewswire - March 9th, 2024 [March 9th, 2024]
- ChatGPT picks 3 low-fee 'Ethereum killers' to buy as ETH gas fees ... - Finbold - Finance in Bold - November 19th, 2023 [November 19th, 2023]
- Title: Unveiling Polkastream: The Evolution of Web 3.0 Entertainment - Medium - November 19th, 2023 [November 19th, 2023]
- PEPE and FLOKI Meet a New Rival: Investor Attraction to ... - BeInCrypto - November 17th, 2023 [November 17th, 2023]
- Why So Many Crypto Games Are Switching ChainsOr Calling it Quits - Decrypt - November 14th, 2023 [November 14th, 2023]
- USDV stablecoin backed by tokenized treasuries launches - crypto.news - November 14th, 2023 [November 14th, 2023]
- What Fueled Polygon's (MATIC) 10% Price Increase? - Investing.com India - November 14th, 2023 [November 14th, 2023]
- SEC and Binance Agree on Protective Order in the Ongoing Legal ... - BSC NEWS - November 14th, 2023 [November 14th, 2023]
- Ethereum vs. Binance Smart Chain: Where to Make More Money - Medium - October 26th, 2023 [October 26th, 2023]
- What Are Trust Wallet Airdrops and How to Claim One? - Latest Cryptocurrency Prices & Articles - October 26th, 2023 [October 26th, 2023]
- Binance Statistics 2023 (Data on Usage, Revenue, and More) - The Tech Report - October 26th, 2023 [October 26th, 2023]
- 10 Cryptocurrencies That Could Explode in 2024 - Analytics Insight - October 26th, 2023 [October 26th, 2023]
- The Rise of Automated Crypto Trading: Strategies and Success Stories - TechiExpert.com - October 26th, 2023 [October 26th, 2023]
- The Best Crypto to Buy Now - Tekedia - October 26th, 2023 [October 26th, 2023]
- Crypto hacks: The Story - The Cryptonomist - October 15th, 2023 [October 15th, 2023]
- Taurus taps Bank of America and SAP veterans to head European ... - Tekedia - October 15th, 2023 [October 15th, 2023]
- Why Are Whales Flooding Everlodge (ELDG)? Bitcoin Cash (BCH ... - The Crypto Basic - October 15th, 2023 [October 15th, 2023]
- Ankr teams up with XDC Network to launch RPC Integration - crypto.news - October 15th, 2023 [October 15th, 2023]
- Binance froze cryptocurrency accounts associated with Hamas amid ... - Tekedia - October 15th, 2023 [October 15th, 2023]
- TangibleDAO Plans Recovery After USDR Stablecoin Crashes - BeInCrypto - October 15th, 2023 [October 15th, 2023]
- The Environmental Impact of Proof-of-Stake Blockchains: A ... - Tribune Online - October 15th, 2023 [October 15th, 2023]
- Binance Coin Hovers Above $200: BNB Smart Chain Users Rise 40% - Watcher Guru - September 11th, 2023 [September 11th, 2023]
- Binance's indecision to freeze BNB wallets drew controversy in this ... - Cointelegraph - September 11th, 2023 [September 11th, 2023]
- 3 Coins Set To Dominate the Market in 2023 Ethereum (ETH ... - Finbold - Finance in Bold - September 11th, 2023 [September 11th, 2023]
- While Bitcoin Battles Inside Price Channel, Traders Are Buying This ... - Captain Altcoin - September 11th, 2023 [September 11th, 2023]
- Binance Airdrop $3 million BNB to Morocco Earthquake Victims - Watcher Guru - September 11th, 2023 [September 11th, 2023]
- ETH Price Prediction: Uncertain Short-Term Outlook, But These ... - Captain Altcoin - September 11th, 2023 [September 11th, 2023]
- BNB Shows Promising Signs As opBNB Launches, Pomerdoge ... - The Crypto Basic - September 11th, 2023 [September 11th, 2023]
- B2BinPay v17 - Breaking down the latest major platform update - Cointelegraph - September 11th, 2023 [September 11th, 2023]
- 4 Reasons The Bitcoin Price Could Hit $50,000 This Winter ... - Finbold - Finance in Bold - September 11th, 2023 [September 11th, 2023]
- Cronos (CRO) Price Insight - With Growing Utility, Can CRO Reach ... - Inside Bitcoins - September 11th, 2023 [September 11th, 2023]
- How to Bridge to Tron - Watcher Guru - August 13th, 2023 [August 13th, 2023]
- Could the SEC Lawsuit End Binance for Good? Analysts Weigh In - Live Bitcoin News - August 13th, 2023 [August 13th, 2023]
- BNB Chain hard fork to improve security and compatibility with EVM ... - Cointelegraph - August 13th, 2023 [August 13th, 2023]
- How To Get Free 10 BNB with PancakeSwap Full Tutorial 2023 - Medium - August 13th, 2023 [August 13th, 2023]
- How to find BEP-20 wallet address on Trust Wallet & Metamask ... - Cryptopolitan - August 13th, 2023 [August 13th, 2023]
- Curved Finance Receives $5 Million FromBinance - cryptonewsbytes.com - August 13th, 2023 [August 13th, 2023]
- Early activity on Coinbase's Base chain shows promising signs - Blockworks - August 13th, 2023 [August 13th, 2023]
- Solana TVL Soars: Outperforms Ethereum, BSC, and Avalanche ... - Crypto News Flash - August 13th, 2023 [August 13th, 2023]
- Developing Automated Market Making on PancakeSwap: Tools ... - Rebellion Research - August 13th, 2023 [August 13th, 2023]