Search code examples
ruby-on-railsreactjswebsocketreal-time

Adding an HTTP event (from Rails server) listener to React.js client


My app is running on Rails server with React client. I can send request from React to Rails with axios, but I don't know how to send request from Rails to React.

When one user follows the other user, I want to show it to the other one in real-time.

Is socket.io something that I should be using? I welcome any kind of recommendations.


Solution

  • You have two basic options when it comes to pushing messages from server-to-client on the web:

    1. HTTP polling: the client simply asks the server every so often -- say, every 5 seconds) if there are any new messages (new followers, in your case). This is easy and effective, but involves a lot of vapid HTTP requests. A variant of this is "long polling", in which the server holds the connection open for a while, but I wouldn't recommend that.
    2. Websockets: this is a protocol in which the browser connects to your backend over a socket-like connection, allowing for long-lasting bidirectional communication. On Rails, Action Cable provides a fairly easy way to hook up websockets and get the interactions you're looking for. Socket.io is another option which has no connection to Rails. On the other hand, a hosted option like pusher would let you get started without needing any new infrastructure (in order to track who's listening across multiple servers, ActionCable needs Redis or another distributed database).