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 change port in Next.js App
Next.js provides the flexibility to change the default port of the development server using command-line options such as -p <port_number> or by updating the "scripts" section in the package.json file, offering developers multiple ways to customize the port configuration based on their requirem
3 min read
How to create Telegram Chatbot with Node.js ?
In this article, we will discuss how to create a telegram chat box with Node.js, with the help of telegram, we can create as many as bots as we want, and we can configure them according to our needs. Nowadays, bots in telegrams are mainly used to protect users from spam or maintain privacy in the te
2 min read
How to Build a Microservices Architecture with NodeJS?
Microservices architecture allows us to break down complex applications into smaller, independently deployable services. Node.js with its non-blocking I/O and event-driven nature is an excellent choice for building microservices. Microservices architecture can involve designing the application as a
3 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 Connect MongoDB Database in a Node.js Applications ?
To connect MongoDB to a Node.js application, you can follow a simple process using the Mongoose library, which provides a flexible way to work with MongoDB. Mongoose acts as an Object Data Modeling (ODM) library, making it easier to structure and interact with MongoDB from Node.js. Prerequisites:Nod
2 min read
How to Setup View Engine in Node.js ?
View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with
2 min read
Introduction to Sockets.IO in Node.js
Socket.IO is a popular library that is used for building real-time web applications. It allows your website and server to talk to each other instantly, making things like live chat and instant updates possible. Socket.IO makes it easy to manage WebSocket connections and events.It works even with old
6 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 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