Why am I seeing every message multiple times?

If your message listener is being called multiple times for every message, one of two things probably happened:

 

1. You are mistakenly instantiating the Realtime library more than once in a single page, and subscribing to the same channels with both. It's very rare you would want to have multiple library instances in a single web page or app -- you can subscribe to hundreds of channel from a single connection, and they are all multiplexed over one websocket. So make sure you only instantiate the library in one place, and keep a single shared reference to it.

 

2. You are mistakenly calling channel#subscribe multiple times with the same listener. For example, in this snippet of code, subscribe() will be called every time the connection goes into the connected state, which may happen multiple times if there's a dodgy internet connection -- and every time it's called, it will add that listener to the channel:

 

// WRONG
realtime.connection.on('connected', () => {
channel.subscribe(msg => console.log('received: ' + msg.name))
});

 

You can fix this by using once, which will only be called at most once:

// BETTER
realtime.connection.once('connected', () => {
channel.subscribe(msg => console.log('received: ' + msg.name))
});
 


Or alternatively, just call subscribe() at the top level, it doesn't need to be called from inside an on-connected callback.

 

For more information, see our comprehensive channel documentation.