DEV Community

Write your own WebSocket middleware for React/Redux in 4 Steps

Lina Rudashevski on July 27, 2019

If you want to use websockets with redux and don't like dependencies, it's not too hard to write your own middleware as long as you understand some...
Collapse
 
desirepeeper profile image
Ali Almohsen

Love it, thanks a lot for the excellent implementation! Quick question though, what's the point of this action which isn't called anywhere and isn't handled in the middleware nor reducer:
export const wsConnecting = host => ({ type: 'WS_CONNECTING', host });

Collapse
 
aduranil profile image
Lina Rudashevski

Thanks for pointing this out, I do indeed have this defined but did not use it in my code. The original intention was to console.log when the websocket was in a connecting state but not yet connected, simply for logging and debugging purposes. I ended up not using it

Collapse
 
hussainahmad profile image
Hussain Sherwani

hi, Thanks for this wonderful library. when I trigger WS_CONNECT automatically 'onClose' websocket handler calling. therefor before connecting with server it will automatically triggering in onClose WS_DISCONNECTED

Collapse
 
farhatrv profile image
Farhat Abbas RV

Hi Lina, loved your post.

Quick doubt - the native JS websocket connection closes after 60 seconds of inactivity. I read almost everywhere to implement a ping-pong based fixed interval communication between clients and server to keep it alive. Do you agree or suggest something else around this problem?

Collapse
 
farhatrv profile image
Farhat Abbas RV

Even sophisticated wrapper like socket.io have same problem if I choose the websocket mode of transportation with them instead of polling.

Collapse
 
toads profile image
Todd Ohanian

Awesome breakdown!

Collapse
 
aduranil profile image
Lina Rudashevski

thanks

Collapse
 
smithphil profile image
Phil Smith

Great article, explains how to write middleware in a very straight forward manner.

Collapse
 
angelojlp profile image
angelojlp

Hi, could you please tell me which version of react and react-redux you have used for this example?
Thank you.