How to Create a Simple Chat Room with JavaScript

The popularity of chat rooms has been an ongoing topic since its peak in the early '90s. While much more sophisticated communication systems carry more weight today, it's still important to understand the basics.

What You'll Learn from this Tutorial

This tutorial explains the steps needed to create a simple JavaScript chat room and your choice of server-side technology, between either PHP or Node.js. The client-side portion, which we'll be discussing here, will work with both server-side solutions.

You'll also learn how to set your username with a JavaScript prompt, store in localStorage, and then pass on your username with a custom message for everyone in the chat room to read.

The best part: The code is clean, easy to set up, and free!  You don't have to sign up or pay for any third-party applications or services to get it working.

What Are WebSockets?

A WebSocket is a computer communications protocol, providing multiple real-time bi-directional communication channels over a single TCP connection.

With standard HTTP and HTTPS connections, a server request is required to respond. The user initiates a page request to a URL, and that data is then returned to the user and displayed in a web browser.

With WebSockets, the idea of a request is different in that you can pass data to and from a server and your users without initiating a full page request.

A few practical examples of WebSocket uses include:

  • Real-time applications
  • Chat rooms or apps
  • Notification handling
  • Online multiplayer games

Initializing WebSockets

Let's dive into some JavaScript code for our chat room and initialize our WebSockets:

var ws_uri = "wss://[your-domain]:9600";
var websocket = new WebSocket(ws_uri);

The ws_uri variable is the URL in which your WebSocket server is running. You'll need to make sure that you change [your-domain] to your correct domain name.

The next line initializes the WebSocket connection so you can begin sending and receiving data.

WebSocket Event Handling

There are a few note-worthy event handlers to consider when setting up your WebSocket functionality. Here are the ones we'll be using in short detail:

  • onopen: Called when the WebSocket connection has opened.
  • onclose: Called when the websocket connection has closed.
  • onerror: Called when an error occurs with the connection.
  • onmessage: Called when a message is received from the server.

Within each of these event handlers, we've added custom messages that will append to the chat-messages container once we created our HTML form, notifying anyone in the chat room of the current connection status.

// on websocket open:
websocket.onopen = function(event) {
MessageAdd('<div class="message green">You have entered the chat room.</div>');
};

// on websocket close:
websocket.onclose = function(event) {
MessageAdd('<div class="message blue">You have been disconnected.</div>');
};

// on websocket error:
websocket.onerror = function(event) {
MessageAdd('<div class="message red">Connection to chat failed.</div>');
};

We'll talk about the MessageAdd() method here in a bit.

To receive messages from the server and display them for all users in the chat room, we need to set up the onmessage event handler:

websocket.onmessage = function(event) {
let data = JSON.parse(event.data);

if (data.type == "message") {
MessageAdd('<div class="message">' + data.username + ': ' + data.message + '</div>');
}
};

This code is pretty simple. The parsed JSON data is stored to our local data variable to be used for checking the message type and outputing the received information.

Submitting Form Data With WebSockets

We're set up our chat room to receive data from the server. Now we need a way to submit custom messages to other users in the chat room:

document.getElementById("chat-form").addEventListener("submit", function(event) {
event.preventDefault();

let message_element = document.getElementsByTagName("input")[0];
let message = message_element.value;

if (message.toString().length) {
let username = localStorage.getItem("username");

let data = {
type: "message",
username: username,
message: message
};

websocket.send(JSON.stringify(data));
message_element.value = "";
}
}, false);

This chunk of code creates an event handler for the chat-form form element we'll create in our HTML form. The message is then pulled from the input field. If the message is at least one character long, a JavaScript object is created to store the username and message text. The websocket.send() method then submits a stringified version of our object to the server, and the input field value is cleared.

Creating Your Chat Room Username

We can easily prompt and set a username by using a little bit of JavaScript magic:

function Username() {
let username = window.prompt("Enter your username:", "");

if (username.toString().length > 2) {
localStorage.setItem("username", username);
}
else {
alert("Your username must be at least two characters.");
Username();
}
}

Username();

The above code snippet uses a JavaScript prompt to allow the user to enter their username.

A minimum of two characters is required for the user to pass validation.  If less than two characters, the user is alerted that the username is invalid and is prompted to enter it again.  If validation is successful, the username is stored in localStorage to be used later when submitting messages.

You can learn more about localStorage here.

You should, of course, find more secure ways to store a username as it can be easily manipulated as a plain string in localStorage.  This is outside the scope of this tutorial and is just to show you how data can be sent via websockets.

Display the Chat Room Messages

Finally, we'll introduce the functionality behind the MessageAdd() method:

function MessageAdd(message) {
let chat_messages = document.getElementById("chat-messages");

chat_messages.insertAdjacentHTML("beforeend", message);
chat_messages.scrollTop = chat_messages.scrollHeight;
}

Here, a message string is passed into the function, containing the input field text from our chat form. The chat-messages container is held in memory while we then append the message using JavaScript's insertAdjacentHTML() method.

At the end of our function, an automatic scroll is pushed to the chat-messages container. This ensures that, as new messages are received from the server, the container scrollbar pushes downward automatically so new messages will continue to remain in view for the user.

The HTML Form

Now, let's wrap everything up by generating our HTML form and chat message display container:

<div id="chat">
<div id="chat-messages">

<form id="chat-form" method="post">
<input type="text" name="message" placeholder="Enter a message..." maxlength="500" autocomplete="off">
<button type="submit">Send</button>
</form>
</div>

This is a very basic form. A chat-messages container is created to hold the messages received from all users, and chat-form is created to hold an input field and submit button to send messages.

Conclusion

This tutorial only touches on the very basics of what WebSockets can do. The possibilities are nearly endless as you get into developing more complex systems.

Before this will function properly, you'll need to either set up a PHP WebSocket server or the Node.js WebSocket server. You'll be required to use HTTPS and WSS protocols in a production environment, so an SSL certificate is also required.

You can view the full JavaScript chat room code here in the GitHub repository.

Additional Learning

Here are some additional tutorials to follow for setting up a hosted environment:

Written by: Josh Rowe, Web Developer

Last Updated: February 23, 2025
Created: April 14, 2020