What is the connection URL for subscribing to events using websockets and Infura?

NETWORK DESCRIPTION URL
Mainnet JSON-RPC over websockets wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID
Ropsten JSON-RPC over websockets wss://ropsten.infura.io/ws/v3/YOUR-PROJECT-ID
Kovan JSON-RPC over websockets wss://kovan.infura.io/ws/v3/YOUR-PROJECT-ID
Rinkeby JSON-RPC over websockets wss://rinkeby.infura.io/ws/v3/YOUR-PROJECT-ID

NOTE: Be sure to replace YOUR-PROJECT-ID with a Project ID from your Infura Dashboard.

Hi, I’m trying to figure out how the websockets are working.
First, there is some confusion on the correct URL. According to OP its wss://<network>.infura.io/ws/v3/<your-project-id>.
According to https://infura.io/docs/ethereum/wss/faq, it’s wss://<network>.infura.io/ws
What is correct?
Second, I’m trying this snippet:

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) {
        console.log(error);
        return console.error(error);
    }

    console.log('Successfully subscribed!', blockHeader);

}).on('data', (blockHeader) => {
    console.log('new block', blockHeader);
});

If run, this snippet does not work, but doesn’t raise any error message as well.

Christoph

Hello Christoph,

I don’t have much JS experience, so I’m not sure why your code is not working, but I tried using the sample code from web3.js website and it’s working fine for me.
https://web3js.readthedocs.io/en/1.0/web3-eth-subscribe.html

I tried ‘newBlockHeaders’ and also ‘pendingTransactions’ just incase and both are working great against wss://mainnet.infura.io/ws/v3/<your+project+id>

Note that you only get blockHeader when a there’s a new block so the subscription function will not necessary immediately return a new block.

as a sanity check, I use wscat to create a ‘newHeads’ subscription. Anytime you get a new block from the newHeads subscription, you should get a console output for new block header.
Here’s how to create newheads subscription using wscat, just incase:

we recommend using your v3 project id

I hope this helps,
Jee

Hi, the wss urls listed above are no longer correct, right?
They should not have /v3

The websocket endpoints listed above are correct and working. We recommend using your project ID that can be found on your infura dashboard

simple example

xxxxx- Jee$ wscat -c wss://mainnet.infura.io/ws/v3/my_v3_key
connected (press CTRL+C to quit)
>

Are they not working for you?