Build A Messaging App Using Socket.io and Node.js

Socket.io is a tool that enables realtime communication between the server and client. It is a JavaScript library with both a client side for the browser and a server side for Node.js. Today I will teach you how to use Socket.io and Node.js to build a simple messaging application. I will go over every step in depth, but it will be helpful if you already have a basic understanding of manipulating the DOM with vanilla JavaScript, using node as a runtime, and some very basic HTML and CSS.

The Set Up

Let’s begin by initializing our application and downloading our dependencies. First create a package.json file to hold our dependencies with:

npm init -y

Then we can install socket.io, and nodemon. Nodemon will allow our server to restart whenever code is changed, making debugging and tracking progress much easier. We can install them both with one command as follows:

npm install socket.io nodemon

These are the only dependencies we will need for this project.

Build the View

We will be using a simple HTML form with some optional CSS to make our messaging app look cleaner. If you have the HTML Boilerplate plug-in installed in your VSCode, you can auto-generate a boilerplate HTML file by typing a single exclamation mark (!) and pressing enter.

Writing out an HTML DOC is fine too

Inside of our HTML we need a few important pieces of code. First of all, we need to create our form element that will act as our message input. Secondly, we will need to include two script tags, one for the server and one for the JavaScript we are going to write.

Our basic HTML

Let’s open a live server to view our HTML page to make sure it is working so far. On mac, the default command for running the live server in VScode is Command+L then Command+O. If this is not working for you, look to the settings on the bottom left of your VScode window for the settings gear. Click on the settings gear, go to command palette, and search for the Live Server: Open with Live Server command. The page in the browser should look like this:

The text in the browser tab is changed in the ‘title’ tag of line 6 in our html

Creating the Server File

The next step is to create a server.js file that will handle all of the actions from socket.io. We start by assigning a variable to define socket.io running at port 3000.We will also write our first function, we will add a listener called ‘connection’ that will execute a function when we are connected to our socket.io server. Our server.js file should look like this:

const io = require('socket.io')(3000)
// creates a server by passing the port number
io.on('connection', socket => {
socket.emit('message', 'Hi There!')
});
//this function is called every time someone loads the site
//each user has their own socket

Now that the server is created and can sends or ‘emits’ a message when user connects to the site, we have to connect our client side to that server. We will create a new file main.js and include the following code:

const socket = io('http://localhost:3000)socket.on('message', data => {
console.log(data)
})
//here 'message' represents the message event name we defined
//in our socket.emit() function

Now if we go to our browser where our Live Server is running, we can check the browser console and see that our message has been sent!

The message we defined in server.js was sent to the browser

Grabbing Message Data

Inside our main.js file, we are going to write some JavaScript to capture the form data from our HTML and assign it to variables so we can work with it. If you haven’t done this before, just follow the example, but basically we are using an event listener on the document object called ‘querySelector’. This allows us to select elements based on different ‘queries’, in this case class because of the period (.) prefix to the text that matches the classname.

const form = document.querySelector('.msg-form')
const formContainer = document.querySelector('.msg-container')
const messageInput = document.querySelector('.msg-input')

We will then add an event listener to the form submission that will emit an event from the socket and send it whatever message we have typed in the form input. So far, our main.js file should look like this:

Display the Message on the Browser

To show our messages on the browser, we simply have to write a function that turns our message into an html tag, append it to our page, and pass that function with our message to the server.

main.js file
server.js

Once we have this set up, we will be able to send messages back and forth from two different browser tabs!

Adding Users

Naturally in a messaging app, it would be pretty useful to know who the messages are coming from. One simple way to establish a user is to use a JavaScript prompt and capture the user in a local variable. We can then send that user, just like we did with the message, to the server and handle it in our on connection function.

We create a user, and we emit the user to the server on line 9. On our server, we want to create an event handler for the ‘new-user’ event that creates a new user and notifies the group when they join.

Now when we message back and forth we see the name of who we are messaging as well as both of our messages, just like a text conversation.

The end result of our basic application

On Styling

There are a number of ways to style this application. Personally I like the idea of having sent messages show up as a different color than received messages by making the following edits to your code and adding a small function, you can make it to that the messages that you send from your browser are different than the ones you receive.

With a little added CSS file your chat app can look like this:

Perhaps not a work worthy of the Guggenheim, but it a little easier to look at and clearer who is sending the messages and who is receiving.

Going Forward

This is a fully functioning but very basic demonstration of the capabilities of Socket.io. I plan to write another blog soon about using Socket.io in a React application with a database, likely Mongo DB. Learn the basics of working with Socket.io first, understand the emit methods and how the client side and server side communicate with each other. And of course, happy coding!

View the Finished Project Here:

Resources:

I ‘m a Web Developer and a Flatiron coding bootcamp alumni. I currently work in the financial tech industry as a Front End Engineer