Create simple chat application using Node.JS, Express.JS and Socket.IO

Introduction

This article is all about creating a simple chatting application using Node.JS, Express.JS, and Socket.IO. There are many different ways to implement this using traditional languages like PHP, .Net, SignalR etc. There are different libraries available in the market like chatJS, jQuery+AJAX. We can also use third-party libraries but they might be paid services. 

Here we are going to implement our own chat application which completely depends on open source technologies and is extremely easy to implement. So before going for the actual implementation lets have a look basic components of this application.

Node.js

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript. Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application’s throughput and scalability. These technologies are commonly used for real-time web applications. Node.js is also called as server side javascript which supports non-blocking event driven IO operations.

Express.js

Express is a framework of Node.js that allows you to use several very useful and powerful features helps you organize your application’s routing and use any templating solution with minimal effort. It also allows for much better organization of your code. Express provides features by extending core functions of Node.js.

Socket.IO

Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and server. It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Both components have a nearly identical API. Like node.js, it is event-driven. Socket.IO provides the ability to implement real-time analytics, binary streaming, instant messaging, and document collaboration.

Getting Started

Now, let’s move towards actual implementation of the application. Here I’m assuming that you have installed Node.js and Express.js successfully and ready to move on. If you have not installed the same yet then do follow the installation steps for both at given link.

Quick steps

  1. Let’s create a folder called chat-application to hold our application files.
  2. Now open NodeJS command prompt/terminal and navigate to your application directory i.e. chat-application.
    cd Desktop\projects\chat-application
    

    Note: I’m using windows machine

  3. Create a package.json file which is the manifest file that describes our project.
    {
     "name": "socket-chat-example",
     "version": "0.0.1",
     "description": "my first socket.io app",
     "dependencies": {}
    }
    

    put above code in package.json and save the file.

  4. Install Express, HTTP, socket.io and path npm modules in your working directory i.e. chat-application.
    npm install --save [email protected]
    npm install http
    npm install socket.io
    npm install path
    

    The above command will result in below screen, You can see all the default packages of express are installed successfully.

  5. Now create a HTML file i.e. index.html which is used to serve the chat window in browser.

    <!doctype html>
      <html>
       <head>
        <title>Chat Application</title>
        <link rel='stylesheet' href='style.css' type='text/css'/>
        <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
        <script src="chat.js"></script>
      </head>
      <body> 
        <ul id="messages"></ul>
        <span id="notifyUser"></span>
        <form id="form" action="" onsubmit="return submitfunction();" > 
          <input type="hidden" id="user" value="" /><input id="m" autocomplete="off" onkeyup="notifyTyping();" placeholder="Type yor message here.." /><input type="submit" id="button" value="Send"/> 
        </form>
      </body>
    </html>

    Here <ul> is used to list the chant messages, <span id=”notifyUser”> is used to notify user that another user is typing the message and the <form> with input box and button is used to send chat messages. put above code in index.html and save the file.

  6. Now create a css file i.e. style.css to design the chat window.
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font: 13px Helvetica, Arial; }
    form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
    form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
    form #button { color:#FFF; background: #2D9F0B; border: none; padding: 10px;  width: 9%; }
    #messages { list-style-type: none; margin: 0; padding: 0; }
    #messages li { padding: 5px 10px; }
    #messages li:nth-child(odd) { background: #eee; }
    #notifyUser { position: fixed; bottom: 42px; width: 100%; }

    put above code in style.css and save the file.

  7. Now create index.js file that will setup our application on server.
    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var path = require('path');
    
    // Initialize appication with route / (that means root of the application)
    app.get('/', function(req, res){
      var express=require('express');
      app.use(express.static(path.join(__dirname)));
      res.sendFile(path.join(__dirname, '../chat-application', 'index.html'));
    });
    
    // Register events on socket connection
    io.on('connection', function(socket){ 
      socket.on('chatMessage', function(from, msg){
        io.emit('chatMessage', from, msg);
      });
      socket.on('notifyUser', function(user){
        io.emit('notifyUser', user);
      });
    });
    
    // Listen application request on port 3000
    http.listen(3000, function(){
      console.log('listening on *:3000');
    });

    Above code translates into the following:

    • First block includes all the modules we are needing in our application
    • Second block initializes out an application on the server
    • Third block registers events on a socket connection
    • Fourth block make the http server listen application requests on port 3000

    The events chatMessage and notifyUser are used to listen to the requests from events emitted by client-side scripts. and based on that server emits the respective events which are then listening by client-side scripts.

  8. Now create file for client side script i.e. chat.js

    var socket = io(); 
    function submitfunction(){
      var from = $('#user').val();
      var message = $('#m').val();
      if(message != '') {
      socket.emit('chatMessage', from, message);
    }
    $('#m').val('').focus();
      return false;
    }
    
    function notifyTyping() { 
      var user = $('#user').val();
      socket.emit('notifyUser', user);
    }
    
    socket.on('chatMessage', function(from, msg){
      var me = $('#user').val();
      var color = (from == me) ? 'green' : '#009afd';
      var from = (from == me) ? 'Me' : from;
      $('#messages').append('<li><b style="color:' + color + '">' + from + '</b>: ' + msg + '</li>');
    });
    
    socket.on('notifyUser', function(user){
      var me = $('#user').val();
      if(user != me) {
        $('#notifyUser').text(user + ' is typing ...');
      }
      setTimeout(function(){ $('#notifyUser').text(''); }, 10000);;
    });
    
    $(document).ready(function(){
      var name = makeid();
      $('#user').val(name);
      socket.emit('chatMessage', 'System', '<b>' + name + '</b> has joined the discussion');
    });
    
    function makeid() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
      for( var i=0; i < 5; i++ ) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
    }

    Above code translates into the following:

    • Initialize socket Io using var socket = io();
      On form submit get the value of input box and emit the chatMessage event along with text message.
    • On keypress event of input box emit the notifyUser along with the name of user to display “xyz is typing” message to the user.
    • Register the event chatMessage which listens to the request from server when user send chat message. Append chat message to the list (<ul>)
    • Register the event notifyUser which listens the request from server when user start typing chat message. Display “xyz is typing” message to the user.
    • On document.ready function create unique user name and emit chatMessage event to send a welcome message.
    • Function makeid() is used to generate unique user name to be display.

    All set, now go to your node command prompt and run the application with the following command.

    node index.js

    The above command will result in below screen

  9. Now go to your favorite web browser and open link(localhost:3000) in two different windows.
  10. Hurrey…!!! we have successfully created a chat application and its working like a charm.

Quick References

  1. http://socket.io/
  2. https://nodejs.org
  3. http://expressjs.com/

I Hope you have enjoyed this tutorial and find it easy to learn, implement and use. A single document which is needed to implement a simple chat application. I have written this tutorial based on my experience and knowledge. There might be some glitches present in this tutorial, please bear with me and let me know if you find any problem. Any suggestions/improvements in this tutorial are welcome.

I have written a new article with an advanced feature of peer to peer chat application.

Special thanks to all readers and followers..!!

90 Comments Create simple chat application using Node.JS, Express.JS and Socket.IO

  1. Sandip Salunke

    There are many people facing issues with working on this application. let me help these people and the one who are going to face the similar problems.

    When you face issue not able to send message, message does not appear, please make sure versions of all your node modules are as per the package.json file in this tutorial. If you have higher versions then you have to make respective change to use those node modules. Or you can install the exact same version as mentioned in package.json.

    If you are still not able to make it work, you can put comment here so that Myself or anyone here can help you to fix it. Make sure you pull in console logs of client(browser) as well as serve to help understand the problem.

    If you want to reach out to me, please connect via
    Email: [email protected] (CC: [email protected])
    Mb.: 8796907719

    Reply
  2. Sandip Salunke

    Hi All,
    I got request for advance version of chat application. I have written a separate article for this, you can read it http://94.143.139.145/node-js/chatbox-a-peer-to-peer-chat-application/

    What’s new there?

    1. Peer to peer chat.
    2. List of online users.
    3. Chat notification with the count of new messages.
    4. Notification sound when a new message comes in from selected and non-selected users.
    5. Assign a user-defined name to the user instead of random ID.
    6. Display username (My name) at top of online users list and as document title.
    7. Improved User experience by changing some CSS properties. Improved chatBox messages UI.

    I hope you will enjoy and find it helpful.

    Thanks!
    Sandip Salunke

    Reply
  3. Sandip Salunke

    Hi All,

    There are few error that people are facing, please follow up with the below steps to resolve those errors.

    1. When user types a message and hit send button, page gets reloaded.
    >> Please try checking console for any error. This is caused because jquery reference is not able to locate the jquery library referenced in index.html. Please update this reference to the latest jquery version.

    2. When user sends a message it just vanishes and not actually sent to any other user.
    >> The reason behind this error is, you installed the latest version of socket.io npm package and your reference to its client version is still pointing to some older version. Try to change its reference in index.html to the new version.

    I hope these are the only commonly faced issues with this tutorial and this will help.

    Reply
  4. Mayank

    For all those who are wondering, why this program is not running.. you should have to upgrade ‘socket.io-1.2.0.js’ to the latest one and it will definitely work.
    Thank you.

    Reply
  5. Prashant Chamoli

    How will others users be able to use this application if I publish it on GitHub?Will they also have to install all npm modules?

    Reply
  6. mani

    hi, it’s very nice tutorial but while i am doing it after typing the message when I click on send button it does not appears. could u please help me on that

    Reply
  7. Aditya Tyagi

    Sir,
    First of all, thank you for this great tutorial. I am facing the same problem some people faced here. As soon as i enter a message, the connection breaks, the page refreshes and a new connection is established. Can you please help me?
    email: [email protected]

    Reply
  8. Phanindra koduri

    HI i’m newbie to node js even though this tutorial help me do step by step even i made progress around it ……

    but i can’t able to see sent message at top tried debugging it by ensuring socket.io,client.js are located in proper directory …… but could not able to made progress could please help me in solving it

    Reply
  9. Jhon

    Hello, everything is fine while i am doing this but, my message after typing in the placeholder is not displaying after clicking the send button. Can you please me help me with this problem? TIA

    Reply
    1. Sandip Salunke

      Please follow below steps
      1. Create a set of emoticon images and their short-codes.
      2. Create a section where you can display all emoticons and on click of them you have to add its short-code in raw message.
      3. When reading and displaying the chat message you have to replace all short-code with their respective emoji icon/image.

      Its bit complex, but yes can be done smartly.

      Reply
  10. jyo

    hi,
    if i want make it as normal chat(conversation panel),i mean user to user.what i have to do.how to host this application.

    Reply
  11. Sreejith BS

    Hi,

    I had a small doubt. In the chat window can we place a button/menu for where user can select the option he want.

    Reply
  12. Anoop

    App is working okay for me , but if i want to change index.html into index.php . The reason of changing is that, I wanna use session value in users name ,, so user can chat by there name rather than randon id .

    Thanks

    Reply
  13. sudip

    package jason file is as follows

    {
    “name”: “iochat”,
    “version”: “1.0.0”,
    “description”: “simple io chat”,
    “main”: “index.js”,
    “dependencies”: {
    “express”: “^4.14.0”,
    “socket.io”: “^1.7.1”,
    “http”: “^0.0.0”,
    “path”: “^0.12.7”
    },
    “devDependencies”: {},
    “scripts”: {
    “test”: “echo “Error: no test specified” && exit 1″,
    “start”: “node server.js”
    },
    “author”: “sudip”,
    “license”: “ISC”
    }

    kindly help me

    Reply
  14. sudip

    hi Mr. sandip,
    i could not able to run the application.
    after creating package jason , I installed http , socket.io , express and path through git bash terminal and initiated “npm install “command to generate node module in that directory.
    then i created index.html,index.js,chat.js and style.css
    and put correct directory at res.sendFile(path.join(__dirname, ‘../iochat’, ‘index.html’));
    When i went to run the application with node index.js command, i found that blank server localhost:3000 is appeared before without any content.
    Kindly help me out.

    Reply
    1. Sandip Salunke

      Yes, its possible. You can use the username storred in your user session instead of generating a random userID.

      Reply
  15. Nayana

    Thank you so much!!!!!
    I have tried the live chat app last 4 hours but its not working, using this tutorial it just done with few mints.
    It’s Help me a lot.

    Reply
  16. architsisodia

    hi how can i use it from remote computer ..I mean i want to use from my friend system… i have given my system ip …but its not working that whole view is coming but chat not working…

    Reply
  17. Shravan

    Awesome tutorial…!!!
    Could you specify the directory structure of project and want to clarify few doubts that why didn’t you install node.js.
    Do we need to put _dirname or it takes automatically.
    When index.js is called.

    Reply
  18. Marquavious Draggon

    Hey! Nice tut man. One that actually works! How would I make this live? I guess Im asking how would I Put this on a www website?

    Reply
  19. Sourav

    I am new in node js .Its really awesome tutorial and helpful for beginer like me.Great job .

    I have used django for my webportal and i want to build chat functionality with user to admin. Basically one(user) to one (Admin).So Please can you help to build to it or can you give me some github project or any other source.

    Thanks in advance !!!!!!!

    Reply
    1. Sandip Salunke

      You need to assign a unique id to each user and establish one to one connection anongst them.

      Actually this is the next assignment you have to try to get better understanding.

      Thanks!!

      Reply
  20. Vipul Malhotra

    I would like to implement this in my application with one more feature that the chat should be saved in DB so that it can be reviewed later.
    Now I would want to DB insertion to take place asynchronously in the background without delaying the response time in this feature.
    Could you please guide a bit on how to achieve this.

    Reply
    1. Sandip Salunke

      Hi Vipul,

      Thanks for using tutorial, I believe you are doing well.

      Regarding your requirement, in order to perform database operations you need to create a REST APIs in any of the backend technology like PHP or .Net and make a ajax calls.

      I hope this will help you, in case you need further help feel free to post here.

      Regards
      Sandio S.

      Reply
    1. Sandip Salunke

      Thank you Minakshi for using this tutorial.

      Minakshi, please do refere your friends to use this tutorial.

      Reply
    1. Sandip Salunke

      Hi Anshul

      Thanks for using this tutorial, I believe you are doing well.

      Regarding you requirement, in order to show the list of connected/online users you need to assign an unique ID’s to each user and on connect event you need to emmit an event to add user in the list.

      I hope this will help you, please feel free if you need further assistance.

      Regards
      Sandip S.

      Reply
    2. Sandip Salunke

      You have to do following things
      – Maintain the list of Online users and show that where ever you want (May be right-bottom corner)
      – As soon as any client (user) joins you need to emit an event say ‘newUserJoined’ and listen that to add user to the list of online users.
      – Similarly, as soon as any client (user) leaves, you have to emit an event say ‘userLeft’ and listen that to remove user from the list of online users.

      I hope this may help.

      Reply
  21. Srinivas

    Hello Its very nice
    It is working only localhost
    I want My own IP
    for that WHat I need to do Please let me know

    Reply
  22. Bhomihar AmitKumar

    Thank for your code,its really helpful,but i want to know that how can i use this chat application in multiple computers….

    Reply
  23. pranava

    Hello, everything is fine while i am doing this but, my message after typing in the placeholder is not displaying after clicking the send button. Can you please me help me with this problem? TIA

    Reply
    1. Sarang Raotole

      Hi Pranava, please check whether external scripts references i.e. socket.io etc are downloaded appropriately and references to internal scripts i.e. chat,js etc are been pointed to appropriate path.

      Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.