How to Create A Real-Time Chat App with Node.js

Building a real-time chat application is a common goal for people who are just beginning to dive into the wonderful world of software development. It makes sense–once you understand how to exchange messages between a node js chat server and clients, a lot of doors open up. You can build social networking platforms, messaging applications, and even multiplayer games. In this post, we will explore how to create a real-time chat app with Node.js.

We are going to build a web app so that anyone who visits our domain or IP address will be able to jump in and start chatting. By the end, we will have a web page with real-time chatting that we can access just by navigating to an IP, and it will look like this:

How to Create A Real-time chat app node.js web app

The skills we build here will enable us to branch out to all sorts of other projects, and we will use the code from this post to write other exciting posts in the future!

Note: This tutorial assumes you are comfortable with navigating the command line of a VPS and basic HTML/CSS.


How to Create A Real-Time Chat App with Node.js: Application Checklist

Okay, so we’ve decided we want to learn how to create a real-time chat app. How in the world are we going to accomplish that? Let’s start by looking at what we need:

•A place to host our node js chat server. Luckily, SkySilk has a lot of great solutions for this requirement!

•Node.js: A javascript framework that will power our application

•Express: a Node.js web application framework

•socket.io: a javascript library that powers real-time web applications. It allows bi-directional communication between clients and servers using sockets

Now that we have a clear direction to go in, let’s set up our app hosting.

Discuss VPS management, development, apps and more on the Official SkySilk Discord!

To the Cloud: Setting Up The VPS

We are going to be hosting our chat app on a virtual private server hosted by SkySilk. For this tutorial, I am going to be using the Standard Nano plan, which checks in at a cool $5 per month. I recommend this plan because it is a good balance of specs and price. It has enough specs to not worry about resources while developing a few applications, and it can also handle inviting a few users to test with, all while costing just five bucks a month. In addition, SkySilk has a Node.js template if you would like to deploy a machine with Node already installed!

View SkySilk VPS Plans

Once you have deployed your machine, log into it via SSH with your favorite terminal/client. 

If you deployed a clean Linux OS, we will first need to install Node. If you used the SkySilk Node.js template, you can skip this step.

Read Also: Node.js 10: Should You Upgrade?

We will also need the node package manager, so install it with this command.

Next, create a directory for your chat app and cd into it.

Create a new node project. NPM will take you through some steps, such as naming your project, giving it a version number etc.

Next, we need to add the dependencies we talked about earlier: express and socket.io.

Now our app directory is set up and good to go, and we can get to coding!

Creating a Node Js Chat Server

The first file we need to create is our main app file. I will call mine app.js. Create a file called app.js and open it with a text editor. Let’s do some basic setup.

Here we are telling our app to use express, starting our server, telling our app to use /client as the directory to serve pages from, and setting /client/index.html as the starting page for our app. This is a pretty standard setup for a Node.js app that uses express.

Next, let’s add the socket.io and basic chat functionality.

Here, we designate several actions if a socket receives a certain event. Some of these event names are reserved by socket.io, such as ‘connection’. Others we have defined ourselves, such as ‘sendMsgToServer’. Let’s take a step by step look at what is going on here.

  1. When a socket connects, we define functions based on events or strings the socket receives
  2. Generate a random id when a user connects and add them to our socket list variable
  3. Define a function when the event ‘sendMsgToServer’ occurs, which loops through our socket list and sends the message to every connected socket with our ‘addToChat’ event
  4. When a socket disconnects, remove them from our socket list
  5. Finally, tell our app to listen on port 4141. Whatever port you choose, make sure it is open and not blocked by a firewall.

This provides us with a basic foundation for our node js chat server. Users can connect, send messages that will be sent to every connected user, and we track when someone disconnects. Congrats, you’ve completed the first major step in learning how to create a real-time chat app!

Save and exit out of editing your app.js file. Start your app by running this command in the project directory.

Your program is now running and ready for users! Users can access your app by navigating to <your_vps_ip_address>:4141, or whatever port you are using. Next, we need our HTML page that will be served to the user. Exit out of your running app with ctrl+c and return to your project directory.

A Real-Time Chat App Web Page

Create the subdirectory ‘client’ in your project directory. Then cd into it and create a page called ‘index.html’. Add the following lines of code to the file.

We have added the script references we need in order for the page to function, and set up some basic HTML elements to display to the user. It isn’t going to do much in its current state though, so let’s fix that!

Add the following lines of code to the index.html file.

We just made two major additions with this code. The first addition is that our page now responds when its connected socket receives an ‘addToChat’ event. It takes the data, creates a new instance a chatCell class, and adds it to the chat scroll view.

The second addition is we respond when a user submits a message. We first prevent the page from refreshing via form submission. Then, we emit the event ‘sendMsgToServer’, with our chat input’s text value as an argument. Our app.js file will then receive the message and send it to all connected sockets via the work we put in earlier. We also clear the form text so the user doesn’t have to backspace to type a new message.

So we can now send and receive messages, but we can definitely add some quality of life improvements. Add this code to your <script> section of index.html.

You may have noticed we previously created a boolean called ‘typing’ that we haven’t used yet. With these new lines of code, we add an event listener to our chat form that sets typing to true while the form is focused, and false once it is no longer focused. We then add an event for when a user hits the enter key. If typing is false, then we focus the chat input so they can begin typing without having to click on the field. If typing was true when the user hit enter, we know they just sent a message, so we blur the input form.

Our chat page is now functional and has some conveniences for our chatters. As a final step in learning how to create a real-time chat app, let’s add some CSS to make it a little easier on the eyes. Add this code to the top of your index.html file.

Now if we navigate to <ip_address>:4141, our chat app looks like this:

Real-time chat app node.js

Not too shabby! One last thing I recommend for a node js chat server that needs to be running consistently–Forever. Forever allows your node app to run without you maintaining an active session with the app. Install it with this command.

Then, in your project directory, use this command to start your app and keep it running.

Now your app will remain up even if you exit the app or close your SSH connection. If you ever need to stop your node js chat server, you can use the following command.

How to Create A Real-Time Chat App With Node.js: A Recap

Whew, we made it to the end. In case you are worried you missed something, here are the two main code files for the app in their entirety.

app.js

index.html

That’s everything we covered in this tutorial code-wise. But this is really just the beginning! You’ve learned how to create a real-time chat app with Node.js, but there is so much more you can do with this knowledge.

How to Create A Real-Time Chat App: Final Overview

In this tutorial, we set up a basic node js chat server that we can use just by navigating to an IP address. There are tons of additions and improvements that can be made to this, such as:

  • prompting users to create a username to distinguish users
  • private messaging based on socket id
  • creating a database for users to register and chat with claimed usernames
  • displaying the total number of users, and adjusting when someone joins or disconnects
  • customize the look and make it your own!

The cool thing about this tutorial is that is is a building block for endless possibilities. You can extend this app to become a social site, multiplayer game, polling system, whatever you can dream of essentially. If you are looking for a community of like-minded people interested in how to create a real-time chat app or other content alike, feel free to join the official SkySilk Discord Channel. This tutorial has reached its end, but you can expect SkySilk to build upon this tutorial and create some cool apps by building on this very code. Happy coding!

Deploy A New VPS


More development tutorials you may like:

How to Connect an iOS App to a MySQL Database

Make a Ruby on Rails Web App

How to Connect an Android App to a MySQL Database

Host a Discord Bot using Discord.js

(Visited 94 times, 1 visits today)