Validate Incoming Messages on the Server

The server must validate every incoming message because users can bypass browser-side validation.

For this application, we will enforce:

  • Username must be a non-empty string.
  • Message must be a non-empty string.
  • Username must not exceed 30 characters.
  • Message must not exceed 1000 characters.
  • Unexpected payload types must be rejected.

Update the chat event handler.

Validate Chat Payload
function validateChatMessage(payload) {
  if (!payload || typeof payload !== 'object') {
    return false;
  }

  if (typeof payload.username !== 'string') {
    return false;
  }

  if (typeof payload.message !== 'string') {
    return false;
  }

  const username = payload.username.trim();
  const message = payload.message.trim();

  return (
    username.length > 0 &&
    username.length <= 30 &&
    message.length > 0 &&
    message.length <= 1000
  );
}

export function registerChatEvents(io) {
  io.on('connection', (socket) => {
    socket.on('chat:send', (payload) => {
      if (!validateChatMessage(payload)) {
        socket.emit('chat:error', {
          message: 'Invalid message payload'
        });
        return;
      }

      console.log('Valid message:', payload);
    });
  });
}

The validation function verifies the payload structure, data types, and maximum lengths before processing the message.

Key Takeaways
  • Never trust incoming Socket.IO payloads.

  • Validate object structure and data types.

  • Apply reasonable limits to incoming messages.