Skip to Content

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.

Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

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 parts are the code is clean and very easy to set up, and it's free.  You don't have to sign up or pay for any third-party applications or services to get it working.  All you need are the code examples below and you're off!

Prerequisites

You'll need the following before you can proceed:

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

The JavaScript Chat Room Code

In this case, we'll be creating a very simple JavaScript chat room to illustrate the fundamentals of how WebSockets work.

First, let's get started by creating our HTML display and form:

<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 to the other users.

Initializing WebSockets

Now let's initialize our WebSockets:

var ws_uri = "ws://[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: An event listener called when the WebSocket connection has opened.
  • onclose: An event listener called when the websocket connection has closed.
  • onerror: An event listener called when an error occurs with the connection.
  • onmessage: An event listener 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, 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) {
var 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.

A check for the data type is then done. This isn't required in all cases. Since we're passing variable type in our object and returning it from the server, I've added it here. This is to illustrate that we could send different types of data to the server and return to the user in real-time, such as a new notification, a new user entering the chat room, etc.

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();

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

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

var 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 created earlier. The message is then pulled from the input field. If the message is at least one character long, a JavaScript object is created holding some data about the message, the user, and the input 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() {
var 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 then 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) {
var 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.

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 code in our GitHub repository.

Posted by: Josh Rowe
Last Updated: March 20, 2024
Created: April 14, 2020

Comments

Sad

3y
Nice!

Reply

George

2y
Thanks for the javascript chat example. I'm trying to run your code in phpstorm in windows under xampp apache2. How do I run your backend server script?

Reply

George

2y
Figured out how to run a php program under xampp.
I'm getting the same error message I get when trying to run websocket.php from the browser:
Uncaught Error: Call to undefined function socket_create()
On line 13! Any ideas?

Reply
 

Josh Rowe

2y
Hey, George. Try enabling websockets in your php.ini configuration file by uncommenting or adding the following line:

extension=sockets

Reply

Jamez

2y
I really love your website design, And good job in the chat-message article, thanks i'll try to run it.

Reply
 

Josh Rowe

2y
Thank you so much for your kind words! I’m glad you’re enjoying the site and finding the tutorials useful!

Reply

Chad

2y
Great work, but for someone that is very new to Node.JS or PHP this is a bit tricky to replicate- I seem to be spending most of my time trying set up a server on my machine rather than getting to the main portion that I am interested in. Don't have access to an external server or domain unfortunately.

Reply
 

Josh Rowe

2y
Hey, Chad. Thanks for your kind words regarding the article. As far as getting a web server / application server set up, it sounds like I should create and include more tutorials to help out with this as it can be a pretty involved process. For now, let me know which operating system and version you're using on your local machine and I'll see what I can do to point you in the right direction!

Reply

Tom

2y
Wow, something from GitHub that actually worked within 15 minutes! Now I need to translate server from php to C.

Reply
 

Josh Rowe

2y
Glad it helped!

Reply

Jomar Lipon

2y
Can websocket run in Cpanel?

Reply
 

Josh Rowe

2y
Check out Laravel Websockets for cPanel. You may run into limitations if you're in a shared hosting environment, so check with your hosting provider if needed to see what options are available.

Reply

Adam Kupics

2y
Hi, all I really wanted, while I'm learning html CSS and JavaScript, is to have a simple chat up and running that I can use while I'm learning.

This is awesome because it does exactly what I wanted it to do, It's simple and not to complicated and I can learn and self study from the easily explainable and relatable description as the tutorial goes on.

Thank you for taking the time to do this, It has been a huge help and I'm using it as a basic chat on my site and I might try styling a little bit myself! The only problem I have is when I send the message, it asks me for my username again. I fear there is something I have missed!

Reply
 

Josh Rowe

2y
Hey, Adam. I'm so glad that everything is working out well for you! As for the username prompt, double check your code in these areas:

1. Make sure you're not calling the Username() method when you submit your message form.

2. Make sure you're adding event.preventDefault(); to the top of your form submit event handler and ensure it's spelled correctly. Omitting this or misspelling it will result in a page refresh.

Reply

Robert McNaughton

1y
I was not getting a response to clients, so I iterated between clients and send the message. I'm not sure if this is something due to my noob environment haha. I had to modify the server code as such:

ws_server.on("request", function(req) {
var connection = req.accept(null, req.origin);
connections.push( connection );
connection.on("message", function(message) {
for ( var i = 0; i < connections.length; i++ ) connections[ i ].sendUTF( message.utf8Data );
});


Reply
 

Josh Rowe

1y
What is your current setup? And which backend solution are you using to handle the websocket communications? I'd be curious to look into this further. Let me know!

Reply
 

Robert McNaughton

1y
So this is probably NOT correct as I'm very new to JS/NodeJS.
Windows 10
Visual Studio Code
Node v18.16.1-x64 (just installed, default vanilla options)
Websocket 1.0.34 (via npm install)
The behavior was the same in all browsers (Chrome, Firefox, Edge) all at latest public versions as of today's date. I suspect maybe there's either a difference in version or setup of websocket but I'm well too ignorant to troubleshoot it. But if there's a better way to handle websockets I'm all for it. Thanks for your time!

Reply
 

Josh Rowe

1y
Hey, Robert. I apologize for the delay in getting back to you. After testing the Node.js websocket code from the GitHub repository, it appears to be outdated. I tested the changes you recommended and got it to work on my end with multiple connections. These changes are now available in the repository. Thanks for bringing this to my attention!

Reply

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.