Real time private chatting app using Angular 2, Nodejs, mongodb and Socket.io – Part 1

Yes, you heard it, Real time private chatting app but using Angular 2, Nodejs and Socket.io. In this article, am gonna show you how to create a private chat application using Angular 2, Nodejs and socket.io with the minimum complexity. Here I am using MongoDB as a database to store messages and users data.

As this article seems lengthy, hence I have divided it into 4 parts. Each part of this article covers unique part in building the Real Time private chatting app.

First part: Covers the prerequisites, server configuration setup and REST API along with socket.io integration on the server.

Second part: Here we will configure our angular application and application Routing. In addition to these, we will implement our application’s services.

Third part: Implementation of Login and Registration functionality.

Four part: Building homepage of the application where the user actually can chat with each other.

 

     Download

     Demo

 




Before going any further, let’s take a look at the final outcome of this application.

Login Page

Real time private chatting app angular 2 login page

Home page

Real time private chatting app home pageIf you are looking for AngularJs (Angular 1.x) chatting application using Nodejs this article is only for you.

Prerequisites

Before, creating this application, please take a look at below article if you are not familiar with the concepts listed below.

  1. Highlight selected row in Angular 2
  2. Angular 2 CRUD application using Nodejs

Real time private chatting app

1. Configuring server and APIs.

Below you can see the directory structure for our server. In the config folder, we have our config files, helper file which contains all the method and files to handle routes.

directory structure:

To create new nodejs project, the best practice is to start with npm init. This command will create a package.json file. Now let’s take a look at package.json file of our server.
package.json:

2.Connecting with database (MongoDB):

Create a db.js file under utils folder and write down the below code. Which is pretty straightforward and easy to understand. Here I am using the mongo-db driver to connect our MongoDB to the server.

db.js:

3. Creating nodejs server.

Now create a server.js file in the root of the folder structure and write below code, which is required to run our server. In the below code, I have required necessary files to run our routes and socket events.

server.js:

4. Creating helper file to run the MongoDB Queries.

Now let’s create a helper.js file inside utils directory and write the down below code. In the below code snippet, I have written each method’s name, description, and parameters required to that respective method.

helper.js:

2. Creating REST API

You might have noticed in server.js I have required the routes.js file. This is file will handle all routes for our chat application. Here I am using helper class by calling its method on the respective routes.

For this application, I have created five routes as listed below,

  • /usernameCheck: To check if the username is available or not.
  • /registerUser: Register the User
  • /login: Login the User
  • /userSessionCheck: To check if the user is online or not.
  • /getMessages: To fetch messages from DB between two users.

routes.js:

3. Creating Socket Events

Till now we have created routes for the application now let’s introduce socket.io on the server side in order to achieve the real-time delivery of messages and real-time update of the chat list.

So let’s create the socket.js inside utils folder.

socket.js:

In the above socket class, I have created two methods listed below,

  1. socketEvents().
  2. socketConfig().

Let’s start with socketConfig() method, In this method, if you notice we are storing the socket id and updating the online status of the user respectively who connects to chat application.
Here I am sending the user id of the user from the angular application, in order to update the socket id and online status.

In socketEvents() method, we are listening chat-list,add-message,logout and disconnect socket events on the server side.

  • On chat-list event: I am emitting the chat-list-response from the server for client-side.
  • On add-message event: I am emitting the add-message-response.Here I am storing the messages by calling the method of the helper class.
  • On logout event: I am emitting the chat-list-response from the server for client-side by logging out the user.

Well for first part that’s it. Here we covered our server side application setup and created the REST API. Also, integrated the socket.io on the server side and created the events required for our application.

In the next part we will build our angular application, see you in the next part.

  • Rezgui Baha Eddinne

    where is the config.js file ?

    • You are a true observer man, Actually config.js is not required for Nodejs.

  • Roshna N

    When I tried to run the code, I am getting some ‘path error’. I followed the steps mentioned below to run the code:

    1) Downloaded the code from your website.

    2) I navigated to /Angular app on Command Prompt and typed the command ‘npm install’ to install the dependencies.

    3) Then I navigated to /Nodejs folder on command prompt and issued the same command.

    4) From the /Nodejs folder, I issued the command “node server.js”

    5) Finally on browser, to view the front end, I typed the following URL: “http://localhost:4000”.

    These are the steps I had followed to run the chat application. It would be highly appreciated if you could suggest me where I possibly could have gone wrong?

    • Hi Roshna,
      Think of them as complete different application.
      The Angular app will run on the port 4200, where our frontend will be displayed. The node will run on the 4000,Here we will send the API resquest.

      To the run the Angular app
      Navigate to to the angular folder -> install deps -> then run ng serve.

      To run nodejs app
      Navigate to to the nodejs folder -> install deps -> then run node server.js.

      This should work, and if it doesn’t work Please share the error here will try to resolve it.

      Thanks,

  • Achiel Volckaert

    Hi, i got these errros, i have no clue… i’m running my mongo, did npm i in both the angular as the node

    Cannot read property ‘0’ of undefined
    TypeError: Cannot read property ‘0’ of undefined
    at new NgCliWebpackConfig (C:_nodeReal time private chatting app using Angular 2, Nodejs, mongodb and Socket.ioAngular appnode_modulesangular-climodelswebpack-config.js:14:43)
    at Class.run (C:_nodeReal time private chatting app using Angular 2, Nodejs, mongodb and Socket.ioAngular appnode_modulesangular-clitasksserve-webpack.js:21:22)
    at C:_nodeReal time private chatting app using Angular 2, Nodejs, mongodb and Socket.ioAngular appnode_modulesangular-clicommandsserve.js:93:26
    at
    at process._tickCallback (internal/process/next_tick.js:188:7)
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! private-chat-app-v3@0.0.0 start: ng serve
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the private-chat-app-v3@0.0.0 start script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR! C:UsersAchielAppDataRoamingnpm-cache_logs2017-11-03T17_19_45_299Z-debug.log

    0 info it worked if it ends with ok
    1 verbose cli [ ‘C:\Program Files\nodejs\node.exe’,
    1 verbose cli ‘C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js’,
    1 verbose cli ‘start’ ]
    2 info using npm@5.5.1
    3 info using node@v9.0.0
    4 verbose run-script [ ‘prestart’, ‘start’, ‘poststart’ ]
    5 info lifecycle private-chat-app-v3@0.0.0~prestart: private-chat-app-v3@0.0.0
    6 info lifecycle private-chat-app-v3@0.0.0~start: private-chat-app-v3@0.0.0
    7 verbose lifecycle private-chat-app-v3@0.0.0~start: unsafe-perm in lifecycle true
    8 verbose lifecycle private-chat-app-v3@0.0.0~start: PATH: C:Program Filesnodejsnode_modulesnpmbinnode-gyp-bin;C:_nodeChatReal time private chatting app using Angular 2, Nodejs, mongodb and Socket.ioAngular appnode_modules.bin;C:UsersAchielAppDataLocalProgramsPythonPython36-32;C:WINDOWSsystem32;C:Program FilesGitcmd;C:Program Filesnodejs;C:Program Files (x86)Elm Platform.18bin;C:UsersAchielAppDataLocalProgramsPythonPython36-32;C:WINDOWSsystem32;C:Program FilesHerokubin;C:UsersAchielAppDataRoamingnpm;C:Program FilesMicrosoft VS Codebin
    9 verbose lifecycle private-chat-app-v3@0.0.0~start: CWD: C:_nodeChatReal time private chatting app using Angular 2, Nodejs, mongodb and Socket.ioAngular app
    10 silly lifecycle private-chat-app-v3@0.0.0~start: Args: [ ‘/d /s /c’, ‘ng serve’ ]
    11 silly lifecycle private-chat-app-v3@0.0.0~start: Returned: code: 1 signal: null
    12 info lifecycle private-chat-app-v3@0.0.0~start: Failed to exec start script
    13 verbose stack Error: private-chat-app-v3@0.0.0 start: ng serve
    13 verbose stack Exit status 1
    13 verbose stack at EventEmitter. (C:Program Filesnodejsnode_modulesnpmnode_modulesnpm-lifecycleindex.js:280:16)
    13 verbose stack at emitTwo (events.js:135:13)
    13 verbose stack at EventEmitter.emit (events.js:224:7)
    13 verbose stack at ChildProcess. (C:Program Filesnodejsnode_modulesnpmnode_modulesnpm-lifecyclelibspawn.js:55:14)
    13 verbose stack at emitTwo (events.js:135:13)
    13 verbose stack at ChildProcess.emit (events.js:224:7)
    13 verbose stack at maybeClose (internal/child_process.js:943:16)
    13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
    14 verbose pkgid private-chat-app-v3@0.0.0
    15 verbose cwd C:_nodeChatReal time private chatting app using Angular 2, Nodejs, mongodb and Socket.ioAngular app
    16 verbose Windows_NT 10.0.15063
    17 verbose argv “C:\Program Files\nodejs\node.exe” “C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js” “start”
    18 verbose node v9.0.0
    19 verbose npm v5.5.1
    20 error code ELIFECYCLE
    21 error errno 1
    22 error private-chat-app-v3@0.0.0 start: ng serve
    22 error Exit status 1
    23 error Failed at the private-chat-app-v3@0.0.0 start script.
    23 error This is probably not a problem with npm. There is likely additional logging output above.
    24 verbose exit [ 1, true ]

    • Achiel Volckaert

      this is the error in the angular btw

  • Sanat Kabi

    Hi finally i have run the code and its working properly .
    Thank you so much for the lovely tutorial ……………

  • singh

    I need a help of yours
    as i integrated chat functionality in my app now the problem is i have to start the server in cmd then i run my application using “ionic cordova run browser”. So i wanted to ask that how to implement like when i run my application it automatically start the server. As i pusblish that app my server must be run all the time.

  • Chang Liu

    thanks for this article!