We take a look at different methods for real-time communication in a simple notification system using Node.js and React

Overview

This article is for anyone who wants to add a real time feature to their application, but does not need the full functionality of a serverless platform like Firebase or library like socket.io. Long polling, SSE (Server-Sent Events), and WebSockets provide a more simple and lightweight alternative that is built into all modern web browsers.

Setup

The client generates a key that uniquely identifies itself. This key is used in a request to the server which contains the notification message.

An internal messaging system is used to pass the message to the appropriate endpoint which in turn sends the message back to the client. I recommend using a tool like Postman to send the request.

So for the purposes of the demo, we are manually sending the request. But, you can think of this action as mocking another client or backend service that is trying to send real time data to a specific client.

app.post('/create-notification', (req, res) => {

  const { type, forClientId, message } = req.body

  switch(type) {
    case 'long-polling':
      eventEmitter.emit('notification-long-polling', forClientId, message)
      break
    case 'sse':
      eventEmitter.emit('sse',forClientId, message)
    case 'socket':
      eventEmitter.emit('socket',forClientId, message)
    default:
      break
  }
  res.send()
})

#websocket #nodejs #react #programming

Exploring Long Polling, SSE, and WebSockets
2.10 GEEK