Send a Message from the Browser
Open public/app.js and implement the message submission logic.
The browser needs to:
- Read the username.
- Read the message input.
- Validate that the values are not empty.
- Emit the
chat:sendevent. - Clear the message input after sending.
The browser should send a structured object rather than a plain string.
Example payload:
{
"username": "John",
"message": "Hello everyone!"
}
Client Validation Is Not Enough
Browser-side validation improves user experience, but never trust client input. The server must independently validate usernames, message content, and payload size.
Message Submission
const usernameInput = document.getElementById('username');
const joinButton = document.getElementById('join-button');
const messageForm = document.getElementById('message-form');
const messageInput = document.getElementById('message-input');
joinButton.addEventListener('click', () => {
const username = usernameInput.value.trim();
if (!username) {
alert('Enter your username');
return;
}
usernameInput.disabled = true;
joinButton.disabled = true;
messageInput.disabled = false;
messageForm.querySelector('button').disabled = false;
});
messageForm.addEventListener('submit', (event) => {
event.preventDefault();
const username = usernameInput.value.trim();
const message = messageInput.value.trim();
if (!username || !message) return;
socket.emit('chat:send', {
username,
message
});
messageInput.value = '';
});The form submission handler validates the message and emits a structured payload to the server.
Key Takeaways
socket.emit() sends data to the server.
Use structured payloads for application events.
Validate user input on both client and server.