How to Configure Socket.IO with Demo-Chat App in Node.js ?
Last Updated :
24 Nov, 2021
For making a chat app, it is required that the server sends data to the client but the client should also respond back to the server. This can be done by making use of the Websockets. A WebSocket is a kind of communication pipe opened in two directions.
Prerequisite:
- Node.js: It is an open source JavaScript back-end technology executed by the server. It has its own package manager npm(Node Package Manager) which allows easy installation of packages.
- Express.js: It is a framework based on Node.js.
- Socket.io: It enables real-time bidirectional event-based communication. It works on every platform, browser, or device, focusing equally on reliability and speed. Socket.IO is built on top of the WebSockets API (Client-side) and Node.js. It is one of the most dependent upon the library at npm.
Setting up the Environment: The very first step is to start npm. So, create a new repository and initialize npm using the following commands:
$ mkdir chatApp
$ cd chatApp
$ npm init
Now, the next step is to install npm packages which will be required in building our chat application.
-
express: The web application framework for Node.js.
-
nodemon:(optional) It is used to restart our server. If you don’t want to install it, simply restart server by writing node app.js in the terminal.
-
ejs: A simple templating language that lets you generate HTML markup with plain JavaScript.
-
socket.io: The package that manages Websocket.
Just run the following commands in your terminal to install the above-mentioned packages:
$ npm install --save express
$ npm install --save socket.io
$ npm install --save ejs
$ npm install --save nodemon
Steps to implement code:
Step 1: Create app.js
const express = require( 'express' );
const app = express();
app.set( "view engine" , "ejs" );
app.use(express.static( "public" ));
app.get( "/" , function (req, res) {
res.send( "Welcome to chat app!" );
});
server = app.listen(3000);
|
If you run http://localhost:3000 in your browser, you can see the message appearing on your screen as shown below:

Now to configure socket.io, we have to first make an object in app.js file as shown below:
const io = require( "socket.io" )(server);
io.on( 'connection' , (socket) {
console.log( "New user connected" );
});
|
Here, the io object will give us access to the socket.io library. The io object is now listening to each connection to our app. Each time a new user is connecting, it will print the following output:
New user connected
Now for building a window for chat application we will make a html file (actually ejs file) named index.ejs inside views folder. On the other side, public folder will contain css file namely style.css and js file chat.js. It will look like this:

We will now create a route which will render our index.ejs file which opens the window of our chat application.
app.get( "/" , function (req, res) {
res.render( "index.ejs" );
});
|
Now if you will run http://localhost:3000 our chat window will look like this:

Now we will install socket.io on each client which will attempt to connect to our server. To do that, we have to import the socket.io library on the client side:
At the end of your body add these lines:
<script src=
</script>
<script src= "chat.js" ></script>
|
Now create a js file named chat.js in the public folder.
Step 2: Sending and Receiving Data Now, we will write some code that will enable us to send data as well as receive data from the server.
Changing Username: First of all, we will set a default username as something let’s say “Xyz”. To do so, write down the following code in the app.js and chat.js file.
Filename: app.js
const io = require( "socket.io" )(server);
io.on( 'connection' , (socket) {
console.log( "New user connected" );
socket.username= "xyz" ;
socket.on( 'change_username' , (data) {
socket.username = data.username;
});
});
|
Filename: chat.js
$ ( function () {
var message = $( "#message" );
var username = $( "#username" );
var send_message = $( "#send_message" );
var send_username = $( "#send_username" );
var chatroom = $( "#chatroom" );
send_username.click( function () {
console.log(username.val());
socket.emit( 'change_username' ,
{ username : username.val() });
});
});
|
socket.emit() allows you to emit custom events on the server and client.
Message: For messages we modify our files as shown below:
Filename: chat.js
$ ( function () {
var message = $( "#message" );
var username = $( "#username" );
var send_message = $( "#send_message" );
var send_username = $( "#send_username" );
var chatroom = $( "#chatroom" );
send_message.click( function () {
socket.emit( 'new_message' , { message : message.val() });
});
socket.on( "new_message" , (data) {
console.log(data);
chatroom.append( "<p class='message'>"
+ data.username+ ";" + data.message+ "</p>" )
});
send_username.click( function () {
console.log(username.val())
socket.emit( 'change_username' ,
{username : username.val()})
});
});
|
Filename: app.js
const io = require( "socket.io" )(server);
io.on( 'connection' , (socket) {
console.log( "New user connected" );
socket.username= "xyz" ;
socket.on( 'change_username' , (data) {
socket.username = data.username;
});
socket.on( 'new_message' , (data) {
io.socket.emit( 'new_message' , {
message : data.message,
username : socket.username
});
});
});
|
Th final result of our simple chat app will look like this:

A Little Advancement: A little more we can do is add a jQuery event listener on typing and send a socket event named typing.
It will simply display if someone is typing a message. Write the following code in chat.js and app.js as shown below:
Filename: chat.js
message.bind( "keypress" , () {
socket.emit( 'typing' );
});
socket.on( 'typing' , (data) {
feedback.html( "<p><i>" + data.username
+ " is typing a message..." + "</i></p>" );
});
|
Filename: app.js
socket.on( 'typing' , (data) {
socket.broadcast.emit( 'typing' , {username : socket.username});
});
|
Similar Reads
How to Create a Chat App Using socket.io in NodeJS?
Socket.io is a JavaScript library that enables real-time, bidirectional, event-based communication between the client and server. It works on top of WebSocket but provides additional features like automatic reconnection, broadcasting, and fallback options. What We Are Going to Create?In this article
5 min read
How to Create and Run a Node.js Project in VS Code Editor ?
Visual Studio Code (VS Code) is a powerful and user-friendly code editor that is widely used for web development. It comes with features like syntax highlighting, code suggestions, and extensions that make coding easier. In this article, we'll show you how to quickly create and run a Node.js project
2 min read
How to Create a Dockerfile in Node.js ?
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. It is something like a shellscript that gathers multiple commands into a single document to fulfill a single task. Prerequisite: Before you can Dockerize any application, you ne
4 min read
How to Create API to View Logs in Node.js ?
Log files are essential for monitoring and troubleshooting applications. They provide insight into the applicationâs behaviour and help identify issues. In a Node.js application, you might want to create an API that allows you to view these logs easily. This can be particularly useful for centralize
5 min read
Deploy a Node.js Application with Azure
Deploying a Node.js application on Azure, a prominent cloud computing platform, has become a seamless process, thanks to its user-friendly interface and integration capabilities. This guide aims to walk you through deploying a Node.js application on Azure using the Azure portal. We will cover essent
4 min read
How to Create HTTPS Server with Node.js ?
Creating an HTTPS server in Node.js ensures secure communication between your server and clients. HTTPS encrypts data sent over the network, providing a layer of security essential for handling sensitive information. This guide will walk you through the process of setting up an HTTPS server in Node.
4 min read
Difference between socket.io and Websockets in Node.js
WebSocket is the correspondence Convention which gives the bidirectional correspondence between the Customer and the Worker over a TCP association, WebSocket stays open constantly, so they permit continuous information move. At the point when customers trigger the solicitation to the Worker it doesn
4 min read
How to Use ChatGPT API in NodeJS?
ChatGPT is a very powerful chatbot by OpenAI that uses Natural Language Processing to interact like humans. It has become very popular among developers and is being widely used for some of its state-of-the-art features, like understanding and interpreting code, and even generating code based on text
4 min read
How to Manage Users in Socket.io in Node.js ?
Socket.IO is a library that enables real-time, bidirectional, and event-based communication between the browser and the server. Managing users in Socket.io and Node.js typically involves handling user connections, disconnections, and broadcasting messages to specific users or groups of users Prerequ
10 min read
How to add new functionalities to a module in Node.js ?
Node.js is an open-source and cross-platform runtime environment built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isnât a framework, and itâs not a programming language. In this article, we will discuss how to add new functi
3 min read