Creating a simple chat using NodeJS and Socket.IO

John Aldrich Bernardo
5 min readMar 11, 2021

Wanting to create your own chat application? Here is a simple guide in creating one using the NodeJS http module and Socket.IO.

Prerequisites for this course:

  • JavaScript Programming
  • Understanding of HTTP, HTML, and NodeJS

Install NodeJS.

Make sure you have already installed NodeJS.

Verify if you already have installed NodeJS on your machine by running `node — version` to your terminal.

Open your code editor.

For this tutorial, I’ll be using VS Code.

Image Source: https://code.visualstudio.com/assets/home/home-screenshot-linux-lg.png

Create a new folder for our project.

In VS Code, just toggle the terminal using CTRL + ` . Enter mkdir simple_chat; cd simple_chat;. You could also type code -r . after, so that our instance of VS Code would reload using our current project directory.

Creating a folder using bash terminal.

Initialize a new npm package using npm init -y .

This would create a package.json for our project. A package.json is a JavaScript Object Notation file used by Node Package Manager to track down our project’s information and dependencies.

`-y` is an option in npm to skip questionnaire.

npm init -y

Create our index.js file

On our index file, import NodeJS http module.

const http = require('http');

Declare the port we would be using (you are free to change this port),

const port = 8000;

Declare our server variable assigned to a new instance of http.Server using http.createServer . The createServer function accepts a callback function receiving a HTTP Request and HTTP Response object.

const server = http.createServer((req, res) => {});

For now, let’s return a Hello HTTP! message in HTML format.

const server = http.createServer((req, res) => {
res.writeHead(200, {'content-type': 'text/html'});
res.end('<h1>Hello HTTP!</h1>');
});

See official documentation for createServer here.

Our code should look like this

Let’s test our simple server by running it using node index.js or by using VS Code’s Debugger (F5).

Output of our Simple Server

Create our Chat Box

Create a new file, named chat.html . Make sure we have an input with id input and a button with id send . Also, don’t forget our list element with id messages where we would place the incoming chat messages.

HTML for our Simple Chat

Now, let’s add this to response of our server. Import path and fs module from NodeJS Standard library. Then render the contents of the chat.html using our server.

Code Preview

Install Socket.IO

Now that we’re done with our chat page, we could now install socket.io . Just run npm install socket.io from your terminal.

installing socket.io

Declare a variable for handling our socket attached to our HTTP server.

const io = require('socket.io')(server)

then, let us add some user connection logging;

Add event handler for connection and disconnection

On our chat.html , add our socket.ioclient and initialize a connection.

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>

Once, you have run our server and opened our application http://localhost:8000 . You would see a log that user is currently online.

user connected

Emitting Events from Client

Open our chat.html , and emit some event once the user clicks on Send button.

Emit message from client

emit is a function in socket.io that would send an event indicated as the first parameter to the server with the value assigned as the second parameter.

Since, we’re creating a simple chat application. Let us name the event message with the value from our input element.

Back on to our server, inside our io connection handler, create an event handling for message event that would basically log to the console the message of the user.

socket.on('message', (message) => {
console.log('user says: ', message);
});

Run our application and try sending some message using our chat box. And see, the message log on to our server.

Example Message Received

Emitting Events from the Server

Now, we’re sending events from our client. We now want our client to receive the events coming from our server instead. But first, we need our server to trigger the event. We could do this by also using aemit function.

emit function from our socket instanfce

For our client to see the events, we could also use the on function to listen for the events that would be triggered by our server.

Example Code

This code would append the message to our list element every time message event is triggered by our server.

Our Simple Chat Application

Once run, every user opened our application would see the message.

Demo

View our project here: https://repl.it/@jabernardo/SimpleChat

What’s next?

There are plenty of opportunities to improve here. Your imagination is the only limit. Here are some ideas:

  • Using express
  • Group Chat with usernames displayed
  • Storing Chat to Database
  • Direct Chat

--

--