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 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 is 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 lets move towards actual implementation of 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 express@4.10.2
    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 application on server
    • Third block registers events on socket connection
    • Fourth block make the http server listen application requests on port 3000

    The events chatMessage and notifyUser are used to listen the requests from events emitted by client side scripts. and based on that server emits the respective events which are being then listen 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 name of user to display “xyz is typing” message to the user.
    • Register the event chatMessage which listens 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 welcome message.
    • Function makeid() is used to generate unique user name to be display.

    We have done with all the coding stuff, now go to your node command prompt and run the application with following command.

    node index.js

    The above command will result in below screen

  9. Now go to your favourite 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 useful. I have tried my best to group everything inside 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.

Special thanks to all readers and followers..!!

By | 2015-07-04T18:25:36+00:00 July 4th, 2015|JavaScript|62 Comments

About the Author:

62 Comments

  1. hanumesh July 6, 2015 at 4:48 am - Reply

    cool , thanks

  2. Sandeep July 7, 2015 at 6:52 am - Reply

    Nice Post.
    It’s helps me a lot 😉

  3. sagar Marathe September 12, 2015 at 5:14 am - Reply

    Awesome Tutorial

  4. pranava October 13, 2015 at 2:13 am - Reply

    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

    • Sarang Raotole January 16, 2016 at 6:46 am - Reply

      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.

    • Tyron June 14, 2016 at 9:28 am - Reply

      im also having the same problem

    • sandeep July 20, 2017 at 7:02 am - Reply

      I am also facing the same issue.
      Sandip Salunke can you please help me regarding this??

  5. Mochila November 26, 2015 at 4:46 pm - Reply

    MUITO OBRIGADO

  6. manoz November 27, 2015 at 5:23 am - Reply

    nice, its working good

    • Sandip Salunke April 2, 2016 at 4:03 pm - Reply

      Thanks for using this tutorial, please do share with your friends.

  7. Bhomihar AmitKumar January 4, 2016 at 11:05 am - Reply

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

    • Sandip Salunke January 27, 2016 at 7:35 am - Reply

      Its a web based demo, you can use this on N number of computers.

  8. Sarang Raotole January 15, 2016 at 4:27 pm - Reply

    Very Nice Demo. Worth reference to start with node chat sample app.

  9. suriya January 23, 2016 at 6:46 am - Reply

    dude… is just bravo man…!!!!!
    i need to clarify few thing with you.. could u pls connect with me ? through hi.jayasurya@gmail.com

    • J Singh January 27, 2016 at 10:51 am - Reply

      Please ask your question here. Some one might be able to answer your question or if i get a chance i will answer the question.

    • Sandip Salunke January 28, 2016 at 5:12 am - Reply

      Hi Suriya,

      You can contact me on sandip.salunke@outlook.com

  10. asim January 26, 2016 at 10:16 am - Reply

    nice demo

  11. ganga January 30, 2016 at 4:21 pm - Reply

    Thanks this was very helpful1!!!

  12. Srinivas February 8, 2016 at 5:20 pm - Reply

    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

    • Sandip Salunke February 10, 2016 at 1:29 pm - Reply

      Hi SRINIVAS,

      Thanks for your interest and review…!!

      It’s a web based application and if you want to execute it using your IP address in browser then you can put your IP address instead of localhost and access the same from remote machine.

      Ex.
      I’m using
      http://localhost/chatApplication
      then you can use
      http://172.16.0.1/chatApplication

      I hope this may help you and makes sense.

      Regards
      Sandip

  13. Oti Mensah Frederick February 9, 2016 at 7:38 pm - Reply

    An awesome tutorial. Thanks.

  14. anshul February 25, 2016 at 10:41 am - Reply

    how to show online user in friends list by using soket io

    • Sandip Salunke April 2, 2016 at 4:00 pm - Reply

      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.

  15. meenakshi February 25, 2016 at 11:55 am - Reply

    nice post

    • Sandip Salunke April 2, 2016 at 3:55 pm - Reply

      Thank you Minakshi for using this tutorial.

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

  16. Vipul Malhotra March 11, 2016 at 10:32 am - Reply

    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.

    • Sandip Salunke April 2, 2016 at 3:49 pm - Reply

      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.

  17. Anil March 15, 2016 at 12:21 pm - Reply

    Awesome

    • Sandip Salunke April 2, 2016 at 3:51 pm - Reply

      Thanks buddy

  18. Gaurav April 1, 2016 at 9:57 am - Reply

    thank you buddy

    • Sandip Salunke April 2, 2016 at 3:53 pm - Reply

      You are well come Gaurav, please do refer your friends to use this tutorial.

  19. Sourav May 28, 2016 at 8:54 am - Reply

    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 !!!!!!!

    • Sandip Salunke June 15, 2016 at 1:27 pm - Reply

      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!!

  20. Marquavious Draggon May 30, 2016 at 11:17 pm - Reply

    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?

    • Sandip Salunke June 15, 2016 at 1:25 pm - Reply

      You can deploy your code to server.

      Thanks!!

  21. Sonali p June 11, 2016 at 8:17 am - Reply

    Thank Working perfectly

    • Sandip Salunke June 15, 2016 at 1:24 pm - Reply

      Thanks Sonali!!!

  22. Basit June 28, 2016 at 11:02 am - Reply

    Nice work

  23. shubham patwa July 5, 2016 at 11:44 am - Reply

    nice tutorial

  24. Shravan August 30, 2016 at 2:28 pm - Reply

    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.

  25. Pratik September 1, 2016 at 12:36 pm - Reply

    Very helpful, thanks

  26. architsisodia September 13, 2016 at 6:04 am - Reply

    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…

  27. ofobrukweta October 18, 2016 at 9:39 am - Reply

    please do you have videos on this described steps above and other videos on exploring the node.js more

  28. ofobrukweta October 18, 2016 at 9:41 am - Reply

    never the less awesome tutorial

  29. Ashu Sahu October 22, 2016 at 5:51 pm - Reply

    Nice post its good example for begine

  30. Nayana November 22, 2016 at 10:32 am - Reply

    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.

    • Joya November 22, 2016 at 11:49 am - Reply

      Awesome tutorial. Thanks a lot.

  31. Vinoth November 30, 2016 at 8:26 am - Reply

    Wow nice it is..
    but i want to show a name in chat interface with with login.
    is it possible with this code

  32. sudip December 16, 2016 at 7:29 pm - Reply

    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.

  33. sudip December 16, 2016 at 7:33 pm - Reply

    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

  34. Anoop January 3, 2017 at 11:51 am - Reply

    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

    • Madhivarman January 10, 2017 at 1:06 pm - Reply

      instead index.html pass index.php the app will work fine…

  35. abhishek January 4, 2017 at 5:52 am - Reply

    nce one

  36. Madhivarman January 10, 2017 at 1:03 pm - Reply

    awsome..common chat room..really great..!

  37. sameer January 17, 2017 at 9:47 am - Reply

    I get a error message no such file or directory index.html…..

  38. Sreejith BS February 9, 2017 at 8:50 am - Reply

    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.

  39. Abinaya Sivaramakrishnan March 7, 2017 at 8:28 am - Reply

    Simply great…

  40. Christian March 7, 2017 at 4:18 pm - Reply

    Great guide. Works flawless.

    How can i set this up using ejs for the view instead of html?

  41. baldau chaurasiya March 11, 2017 at 5:58 am - Reply

    how can i setup with php index.html

  42. jyo March 28, 2017 at 4:17 pm - Reply

    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.

  43. Phanindra koduri July 16, 2017 at 5:34 am - Reply

    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

Leave A Comment