Real time notifications using socket.io, NodeJS and angular

We have many time got such requirement as a software developer to send some notification in real time. Today I will show some basics of how to achieve the same.

We will use NodeJS, Angular, Express and Socket.io to achieve real time notification.

Before we start let’s clear some terminology for socket.io/eventEmmiter

What Socket.IO is

Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server.

emit: Send the event

on: Listen for the event

Let’s start with backend first

Create a node service or use any existing service if have any. (I am not showing how to create that as there are many article about creating node service).

Once we are done with initial structure of node service, let’s install socket.io npm module using below command (I am using 3.1.0 version of socket.io)

npm i socket.io

Here is the link for the npm module.

https://www.npmjs.com/package/socket.io

After installing module we will use it in our entry file of node service i.e. app.js, server.js, index.js what ever is your entry file for node service.

In above code snippet we can see at line number 28 that we have initiate socket.io

Here we have passed path while initiating socket.io, so when we will be getting event from UI it will use this path, you can take it as simple API endpoint. And we have also passed server while initiating socket.io

To avoid unnecessary code in our entry file i.e. index.js we will not write our code in index.js

On line number 31 we can see we have required notification controller and passed io.

Path value i.e path: ‘/notification/’ is the name of the path that is captured on the server side.

The server and the client values must match (unless you are using a path-rewriting proxy in between):

Below is the code for socket.io initialization.

Server

const httpServer = require(“http”).createServer();
const io = require(“socket.io”)(httpServer, {
path: “/my-custom-path/”
});

For more on path and server initialization with socket.io please refer below url

https://socket.io/docs/v4/server-initialization/#Socket-IO-server-options

Now create a folder named as controller and create a js file under it named as notification and add code as per below code snippet.

The Socket.IO API is inspired from the Node.js EventEmitter, which means you can emit events on one side and register listeners on the other

Here on line number 3 we can see we have passed io as params.

At line number 4 we have stablished the connection.

At line number 5 we are listening an event which will help us to join users, which we can see at the line number 6, So now the id which we have passed in socket.join will be able to get notification as it has joined the event.

At line number 10 we are listening for event sendNotification which we will get from client. In that event we are sending or emit event ‘recieveNotifications’ to specific user by using io.to() here we can use either io.to or io.in both are same, we just need to pass the group or channel name here.

If you want to send the notification to every user then use socket.broadcast.emit(‘eventName’, data);
});

We are done with our backend part. Now we will be focusing on client side.

Create a new angular project or use any existing if have any, I am not showing how to create one as there are many article for the same. I am using angular 9 here.

After done with the setup, we need to install socket.io-client module ( I am using 3.1.1 version of socket.io-client).

npm i socket.io-client

Select a component in angular or create a new component where you want to use the socket.io.

In that component import the module as per below

import { io } from ‘socket.io-client’;

Now we need to initialize it at UI as we have initialized it at backend.

const socket: any = io(“http://localhost:9000", {

path: “/notification/”

});

We can see path here as well as we have used it in backend, make sure to have same value for path at both the side client and server. We have passed the URL for our backend i.e. http://localhost:9000 where 9000 is the port for our server.

After this we will make the connection as per below

socket.on(‘connection’, () => {

});

Now we need to emit the join event, which we are listening at our server side.

const params = {

sender: sessionStorage.getItem(‘user_id’)

}

socket.emit(‘joinNotifications’, params, () => {

});

Here we have passed the unique id in param to make user join.

Now we need to create an event to send the notification to our server.

socket.emit(‘sendNotifications’, {

message: `You clicked on ${button}.`,

sender: sessionStorage.getItem(‘user_id’),

reciever: sessionStorage.getItem(‘user_id’)

}, () => {

})

Above code snippet will help to send the notification to server from where we can send it to the required users.

Now we need to create an event which will help us to listen the event from server.

socket.on(‘recieveNotifications’, request => {

this.notifications.push(request);

this.notification = this.notifications.length;

})

Above code snippet will help to listen recieveNotifications event from server.

Below is the complete code snippet.

Now we will be having some simple UI from where we will be triggering event.

Now we can start our server with nodemon and our angular app with ng s.

Here I have not covered the authentication part, so you have to complete that and store user id in local storage/session storage/cookies and use it in the code.

Below is the screen recording of real time notifications

Conclusion

We have seen how to create a very simple real time notification feature using nodeJS, angular, express, socket.io, we can also use mongoDB to store data.

If you want to go in more depth please follow below url:

Here is the emit cheat sheet, hope it will help you

Let me know if any part is not clear in comment or please share our thoughts about it.

I am a MEAN stack developer with 3+ years of experience working with one of the most innovative talent product and platform company SCIKY.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store