Last Updated: November 04, 2021
·
4.747K
· Dimitris Stoikidis

Instant order notifications using nodejs & Socket.io

Imagine we have a SAAS application where restaurant owner for example can create their online store and start taking orders from clients online. We need a simple mechanism to notify them as soon as their client completes a new order for their store in order to read it and execute it instantly.

We'll use Heroku to host our nodejs application

On the server

basically here we wait for messages from the clients and inform the store owners/managers app.

var app = require('express')
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server);


var port = process.env.PORT || 3000;
server.listen(port);

io.sockets.on('connection', function (socket) {

    socket.on('join room', function(data) {
        socket.join(data.room);
        console.log("joined room" + data.room);

    });
    socket.on('orderCompleted', function (data) {
        socket.broadcast.to(data.room).emit('notifyStore', data)

    });
});

Client posting order

First we need to include the following file

https://whateveryourappnameis.herokuapp.com/socket.io/socket.io.js

in the store's frontend (where users post theirs orders) and on the backend (where managers read new orders for their store)

Frontend

When clients open a store to make a new order we first join them to the room of that store (we use store_id)

<script>
room_id = 4001 // You can set the id here for each store dynamically
// Connect to socket 
var socket = io.connect('https://whateveryourappnameis.herokuapp.com');
// Emmit message joining room
socket.emit('join room', {
        message: "Joining Room",
        username: "soctaste",
        room: room_id
});
</script>

and on complete order action we send a message to the server

socket.emit('orderCompleted', {
  message: "It looks like you have a new order !!",
  username: "soctaste",
  room: room_id
});

Backend

so in the page we have for store owners/managers were they can check their orders
we join the room with the store id and wait for notifications from the client

var socket = io.connect('https://whateveryourappnameis.herokuapp.com');
socket.emit('join room', {
    message: "Joining room",
    username: "soctaste",
    room: store_id
});

socket.on('notifyStore', function (data) {
    if (data.message) {            

      // Notify user (play a sound etc)        

    } else {
        console.log("There is a problem:", data);
    }

});