Implement Message Acknowledgements

Socket.IO passes an acknowledgement callback to the server when the client provides one.

We can use this callback to return a success or failure response.

Update the server-side message handler to validate the payload and respond through the acknowledgement callback.

Server Acknowledgement
socket.on('chat:send', (payload, acknowledge) => {
  if (!validateChatMessage(payload)) {
    acknowledge?.({
      success: false,
      error: 'Invalid message payload'
    });
    return;
  }

  const chatMessage = {
    username: payload.username.trim(),
    message: payload.message.trim(),
    timestamp: new Date().toISOString()
  };

  io.emit('chat:message', chatMessage);

  acknowledge?.({
    success: true,
    message: 'Message accepted by server'
  });
});

The server invokes the acknowledgement callback after validating and broadcasting the message. Optional chaining allows the handler to work even when the client does not request an acknowledgement.

Key Takeaways
  • Acknowledgement callbacks are supplied by the sender.

  • The receiver invokes the callback to return a result.

  • Use structured responses to communicate success and failure.