HTML5 Push Notification System Using Nodejs MySQL Socket.io

Real-time web/mobile application is becoming popular day by day. Services like Firebase and Pusher provides API’s and Services to develop effective real-time notification system for your mobile and web apps.

We are not going to use these Services in this post; instead, we will develop an application that pops up a notification on a particular event – Say a new comment added on Post. For notification, we will use Chrome desktop notification and for real-time communication – Socket.io.

Prerequisites :

Level of the tutorial is Medium. Knowledge of Node.js and Socket.io is required.

Points to be covered :

Installation and Setup.

Application flow.

Database design.

Setting up Grunt.

Server.

Client.

Socket.io integration.

Notification integration.

Running the app.

Installation and setup.

We need following node modules :

socket.io

mysql

express

grunt

grunt-nodemon

grunt-jshint

Create new package.json file and paste following code. Use npm init to create package.json file;It’s a best practice.

package.json

{"name":"socket-notification","version":"1.0.0","description":"Real time notification system using Socket.io and ExpressJS","main":"./Server/","scripts":{"start":"node ./Server/"},"author":"","license":"ISC","dependencies":{"express":"^4.13.3","socket.io":"^1.3.6","mysql":"~2.9.0"},"devDependencies":{"grunt":"^0.4.5","grunt-contrib-jshint":"^0.11.3","grunt-nodemon":"^0.4.0"}}

Install dependencies using

npm install

Directory setup.

Application Flow :

To keep the demo simple, I have one constant status in database and user will add a comment on that. As soon as someone posted a comment all users except the one who have made the comment will receive desktop notification immediately.

Socket.io will be responsible for detecting events and information back-end as well as a client about the same.

Database design :

The database is in MySQL and it’s quite simple; It contains 3 tables and they store Status, User and Comment information. Comment is linked to the User table with a foreign key. Status table linked to User table too with a foreign key so that we ensure only registered User can add Status and Comments.

Open PHPMyAdmin and create new Database name as socketDemo and then import the SQL file provided in Source code. This will create tables and add data needed to run the application.

Setting up Grunt.

Grunt is one of the popular task runner module used for running various tasks ( Code quality checking, uglify, etc ) before starting the Node Server. This makes sure your code passes various task before it actually runs. Here is the following task we will run using Grunt.

This is the basic view. We will add ajax calls, socket, and notification in the next section.

Socket.io integration.

We have our Server and Client ready. Let’s add Socket support. In Server.js file, we have required socket in io variable. Let’s use it to develop our simple socket handler.

First of all we need to recognise Is the user connected ? This code will do.

io.on('connection',function(socket){// This event will trigger when any user is connected.// You can use 'socket' to emit and receive events.});

Next step is we need to detect whether a particular event happened or not? In our case, **”did someone added a comment ?” **.

Let’s name this event as “comment added”, so in order to listen to this in the back-end, you need to use the following code.

io.on('connection',function(socket){// This event will trigger when any user is connected.// You can use 'socket' to emit and receive events.
socket.on('commend added',function(data){// When any connected client emit this event, we will receive it here.});});

In order to generate any event, we can use .emit() function and if you want to emit an event to broadcast it to everyone but not the one who has generated you need to use the following code.

io.on('connection',function(socket){// This event will trigger when any user is connected.// You can use 'socket' to emit and receive events.
socket.on('commend added',function(data){// When any connected client emit this event, we will receive it here.
io.emit('something happend');// for all.
socket.broadcast.emit('something happend');// for all except me.});});

Notification integration.

You can see the function notifyMe() that will generate the notification window. I have explained the code in detail here.

notifyMe(user,comment) function

// Let's check if the browser supports notificationsif(!("Notification"in window)){
alert("This browser does not support desktop notification");}// Let's check if the user is okay to get some notificationelseif(Notification.permission==="granted"){// If it's okay let's create a notificationvar options ={
body: message,
dir :"ltr"};var notification =new Notification(user +" Posted a comment",options);}// Otherwise, we need to ask the user for permission// Note, Chrome does not implement the permission static property// So we have to check for NOT 'denied' instead of 'default'elseif(Notification.permission!=='denied'){
Notification.requestPermission(function(permission){// Whatever the user answers, we make sure we store the informationif(!('permission'in Notification)){
Notification.permission= permission;}// If the user is okay, let's create a notificationif(permission ==="granted"){var options ={
body: message,
dir :"ltr"};var notification =new Notification(user +" Posted a comment",options);}});}// At last, if the user already denied any notification, and you// want to be respectful there is no need to bother them any more.}

Further study

Conclusion :

Real-time notifications are catchy part of any web application. There are other Services like Pusher which provides push-notification to both browser and mobile apps. We will cover them in coming posts.

63 Comments

http
Greetings! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly?
My site looks weird when viewing from my
apple iphone. I’m trying to find a template or plugin that might
be able to resolve this issue. If you have any recommendations,
please share. Many thanks!

I tried this code but it is not working. It give me no error but when I debug the code then found this function
socket.on(‘notify everyone’, function (msg) {
notifyMe(msg.user, msg.comment);
});
gives the timeout error and notifyMe function is not called.
Please help if you know solution

Hi,
In my client index.html if I have commented below line ,still I am getting notification .So I just wanted to what is the use of this below line in index.html
socket.on(‘notify everyone’,function(msg){
notifyMe(msg.user,msg.comment);
});

I ran your code , installed the database and seemingly everything was ok , but to post comments , nothing happens , no error occurs . I am using the version version 51.0.2704.103 m Chrome . Sorry my english

Hello,
I have the following warning : “EventEmitter memory leak detected. 11 error lisner added …”. When I click multiple time on the comment button it seems that it goes to an error. Does it initiat another lisner each time I click on “comment” ?
nb : I don’t get the comment puhed. I don’t know why yet.

i’ve test this and works good, when i push mi first notification, however in the next ones clients are recieveing “++1” notifications (whith the last content) for each time i press “comment” button…. is there a way to solve this?

seems like it initiate a new listen every time i click on “comment”, because the first time i push a comment, it send the notification to me and to any other clients connected to the app…. the second time i click comment, it sends not one, but two notifications to all clients….. the third time, 3 notifications.. and so on…..plus, clients must click once at “comment” button to start recieving the notifications ( i’ve solve this, but not the duplicated notifications issue)

sry for my bad english, hope u can get my point and help me with this 🙂

You shouldn’t commit the node_modules folder. People dun do that. Let people who download the source to run the npm install by themselves. On windows unzipping the node_modules is breaking coz of long folder and filenames.

can you help me on this error ?
(index):40 Uncaught ReferenceError: io is not defined
at HTMLDocument. ((index):40)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at Function.ready (jquery.min.js:2)
at HTMLDocument.I (jquery.min.js:2)

Could you please tell us mysql setup.. i am new in database things.. do we need to install my sql on machin ? I didnt get your “Open PHPMyAdmin and create new Database name as socketDemo and then import the SQL file provided in Source code. This will create tables and add data needed to run the application” . Please help me on this.

I did the same but the way you showed the tables in your tutorial and my tables after loading the .sql file is completely different.
After loading the file do we need to do create any relations.
I tried but I am getting the db Error in console.
–thanks.

If you put it inside the on click handler, when one client issues the first comment, it is supposed to be broadcasted to all other clients, but all other clients’ event listeners for ‘notify everyone’ events have not been generated yet, due to the fact that it is inside the on click handler.
Putting it inside the on click handler has another problem: everytime you click the button, you generate a new event listener, and for each event listener you have one notification => you will have multiple notifications, exactly the same, for just one client

I am very happy after studied your blog because you keep up on accurate content of blog and you well known about related subject. Hey i am Jim Witt and i am also found a blog complete relating with your blog then you can also read it.