Home > Net >  Express routes with Socket IO Node JS
Express routes with Socket IO Node JS

Time:02-01

I'm creating a microservice with NodeJS which will send & receive messages with socketIO. I'm following a boilerplate and setup the GET & POST routes with ExpressRouter

socket.on('sendmessage', (newMessage) => {
    socket.in(userId).emit('newmessage', newMessage);
});
app.post('/sendMessage', expressAsyncHandler(async function (req, res) {
  // saving the message to database and returning a response....
}))

I'm just confused about do I need routes if I can handle saving messages functionality too in socketIO? What is the best case for an application like that which ensures message delivery and no data loss?

CodePudding user response:

Whether to use routes or not depends on the design and architecture of your application. If you need to implement additional functionality outside of sending and receiving messages, such as authentication or data validation, using routes with Express is a good option. If your application is solely focused on sending and receiving messages, then you can handle the functionality within the socket.on() event.

For ensuring message delivery and avoiding data loss, you can implement message acknowledgment or implement a message queue like RabbitMQ or Apache Kafka to buffer messages before they are processed by the server. This helps ensure that messages are not lost even if the server goes down or there is a connection issue.

CodePudding user response:

It depends on your specific use case and architecture. Here are a few reasons why you might still want to use express routes in addition to socket.io:

  1. Separation of concerns: Keeping the database interaction separate from socket communication allows for a cleaner and more maintainable codebase.

  2. Scalability: If you want to add more functionality to your application, such as authentication or logging, it can be easier to do so through express routes.

  3. Persistence: Express routes can be used to persist the data to a database, ensuring that data is not lost if the server restarts or a user disconnects.

  4. Security: Express routes can be secured with middleware and authentication mechanisms, preventing unauthorized access to sensitive data.

In summary, it's a good idea to use both express routes and socket.io, especially for a message delivery system where data persistence and security are important considerations.

  • Related