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'),
  'provider in web3 eth: ' + JSON.stringify(web3lib.currentProvider),
console.log('New block in web3 eth: ' + web3lib.blockNumber);
var subscription = web3lib.eth.subscribe('newBlockHeaders', function(
) { 
   if (!error)
       console.log("output of web3 stream"+JSON.stringify(result));
  console.log('Error of web3 stream ' + JSON.stringify(result));

What am I doing wrong here?


was fixed on web3@1.0.0-beta.36 https://github.com/ethereum/web3.js/issues/1559#issuecomment-412348642

| improve this answer | |

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


| improve this answer | |
  • 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 '18 at 13:58
  • Did you try with any other version? – Daniel Luca CleanUnicorn Jul 22 '18 at 13:08
  • 0.20.6 version worked on HTTP and it doesn't have Websocket. Which version are you using? – Sundar Jul 23 '18 at 10:32
  • web3@1.0.0-beta.34 – Daniel Luca CleanUnicorn Jul 23 '18 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 '18 at 18:55

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


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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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