I receive this error when I'm trying to connect to the websocket

WebSocket connection to 'wss://ropsten.infura.io/ws' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

Code snippet

import web3 from 'web3';
var web3lib = new web3(
  new web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws'),
);  
console.log(
  'provider in web3 eth: ' + JSON.stringify(web3lib.currentProvider),
);  
console.log('New block in web3 eth: ' + web3lib.blockNumber);
var subscription = web3lib.eth.subscribe('newBlockHeaders', function(
  error,
  result,
) { 
   if (!error)
       console.log("output of web3 stream"+JSON.stringify(result));
       else
  console.log('Error of web3 stream ' + JSON.stringify(result));
}); 

What am I doing wrong here?

It seems a value of WebSocket request header is invalid.

More specifically say, a value of Sec-WebSocket-Protocol is undefined.

According to the github issue below, the issue was introduced from web3@1.0.0-beta.34

https://github.com/ethereum/web3.js/issues/1559

I confirmed web3@1.0.0-beta.35 has not fixed the issue yet in my environment. So downgrading to web3@1.0.0-beta.33 is needed if you use WebSocket at this moment.

  • 1
    Yeah downgrading worked for me. Thanks for the find. – Sundar Aug 9 at 12:42
  • Still now also? – mesqueeb Sep 6 at 8:06

This is working

#!/usr/bin/env node
const Web3 = require('web3');

const web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws'));

const subscription = web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
if (error) return console.error(error);

console.log('Successfully subscribed!', blockHeader);
}).on('data', (blockHeader) => {
console.log('data: ', blockHeader);
});

// unsubscribes the subscription
subscription.unsubscribe((error, success) => {
if (error) return console.error(error);

console.log('Successfully unsubscribed!');
});

Took this example provided by https://github.com/egalano

https://github.com/INFURA/infura/issues/29#issuecomment-365128914

  • I am again getting the same error for this piece of code also. I am using web3.js 1.0.0-beta.34. Would that be a problem or else what to check? – Sundar Jul 20 at 13:58
  • Did you try with any other version? – cleanunicorn Jul 22 at 13:08
  • 0.20.6 version worked on HTTP and it doesn't have Websocket. Which version are you using? – Sundar Jul 23 at 10:32
  • web3@1.0.0-beta.34 – cleanunicorn Jul 23 at 10:42
  • I updated to web3@1.0.0-beta.35 and started getting the same error. Wouldn't happen with beta-34 or beta-33 – Gus Aug 1 at 18:55

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.