Building a chat – Browser Notifications with React, Websockets and Web-Push 🤯

In the previous article in this series, we talked about Socket.io, how you can send messages between a React app client and a Socket.io server, how to get active users in your web application, and how to add the "User is typing..." feature present in…

Author:Nevo David
Nevo David

What is this article about?

We have all encountered chat over the web, that can be Facebook, Instagram, Whatsapp and the list goes on.Just to give a bit of context, you send a message to a person or a group, they see the message and reply back. Simple yet complex.

In the previous article in this series, we talked aboutĀ Socket.io, how you can send messages between a React app client and a Socket.io server, how to get active users in your web application, and how to add the ā€œUser is typingā€¦ā€ feature present in most modern chat applications.

In this final article, we’ll extend the chat application features. You will learn how to keep your users engaged by sending them desktop notifications when they are not online and how you can read and save the messages in a JSON file. However, this is not a secure way of storing messages in a chat application. Feel free to use any database of your choice when building yours.

Novu – the first open-source notification infrastructure

Just a quick background about us. Novu is the first open-sourceĀ notification infrastructure. We basically help to manage all the product notifications. It can beĀ In-AppĀ (the bell icon like you have in Facebook – Websockets), Emails, SMSs and so on.I would be super happy if you could give us a star! And let me also know in the comments ā¤ļø https://github.com/novuhq/novu

How to send desktop messages to users

Here, I’ll guide you through sending desktop notifications to offline users when they have new chat messages.

In the previous article, we created theĀ ChatFooterĀ component containing a form with an input field and a send button. Since we will be sending a notification immediately after a user sends a message, this is where the desktop notifications functionality will exist.

Follow the steps below:

Update theĀ ChatFooter.jsĀ component to contain a function namedĀ checkPageStatusĀ that runs after a message is sent to the Socket.io server. The function accepts the username and the user’s message.

import React, {useState} from 'react'

const ChatFooter = ({socket}) => {
    const [message, setMessage] = useState("")
    const handleTyping = () => socket.emit("typing",`${localStorage.getItem("userName")} is typing`)

    const handleSendMessage = (e) => {
        e.preventDefault()
        if(message.trim() && localStorage.getItem("userName")) {
        socket.emit("message", 
            {
            text: message, 
            name: localStorage.getItem("userName"), 
            id: `${socket.id}${Math.random()}`
            }) 
                //Here it is \ud83d\udc47\ud83c\udffb
        checkPageStatus(message, localStorage.getItem("userName")) 
        }}
        setMessage("")
    }

    //Check PageStatus Function
    const checkPageStatus = () => {

    }

  return (
    
        
           setMessage(e.target.value)}
            onKeyDown={handleTyping}
            />
            SEND</button>
        </form>
     </div>
  )
}

export default ChatFooter;

Tidy up theĀ ChatFooterĀ component by moving theĀ checkPageStatusĀ function into aĀ src/utilsĀ folder. Create a folder namedĀ utils.

cd src
mkdir utils

Create a JavaScript file within theĀ utilsĀ folder containing theĀ checkPageStatusĀ function.

cd utils
touch functions.js

Copy the code below into theĀ functions.jsĀ file.

export default function checkPageStatus(message, user){

}

Update theĀ ChatFooterĀ component to contain the newly created function from theĀ utils/functions.jsĀ file.

import React, {useState} from 'react'
import checkPageStatus from "../utils/functions"
//....Remaining codes

You can now update the function within theĀ functions.jsĀ file as done below:

export default function checkPageStatus(message, user) {
    if(!("Notification" in window)) {
      alert("This browser does not support system notifications!")
    } 
    else if(Notification.permission === "granted") {
      sendNotification(message, user)
    }
    else if(Notification.permission !== "denied") {
       Notification.requestPermission((permission)=> {
          if (permission === "granted") {
            sendNotification(message, user)
          }
       })
    }
}

From the code snippet above, theĀ JavaScript Notification APIĀ Ā is used to configure and display notifications to users. It has three properties representing its current state. They are:

  • Denied – notifications are not allowed.
  • Granted – notifications are allowed.
  • Default – The user choice is unknown, so the browser will act as if notifications are disabled. (We are not interested in this)

The first conditional statement (if) checks if theĀ JavaScript Notification APIĀ is unavailable on the web browser, then alerts the user that the browser does not support desktop notifications.

The second conditional statement checks if notifications are allowed, then calls theĀ sendNotificationĀ function.

The last conditional statement checks if the notifications are not disabled, it then requests the permission status before sending the notifications.

Next, create theĀ sendNotificationĀ function referenced in the code snippet above.

//utils/functions.js
function sendNotification(message, user) {

}
export default function checkPageStatus(message, user) {
  .....
}

Update theĀ sendNotificationĀ function to display the notification’s content.

/*
title - New message from Open Chat
icon - image URL from Flaticon
body - main content of the notification
*/
function sendNotification(message, user) {
    const notification = new Notification("New message from Open Chat", {
      icon: "https://cdn-icons-png.flaticon.com/512/733/733585.png",
      body: `@${user}: ${message}`
    })
    notification.onclick = ()=> function() {
      window.open("http://localhost:3000/chat")
    }
}

The code snippet above represents the layout of the notification, and when clicked, it redirects the user toĀ http://localhost:3000/chat.

Congratulations!šŸ’ƒšŸ» We’ve been able to display desktop notifications to the user when they send a message. In the next section, you’ll learn how to send alerts to offline users.

šŸ’” Offline users are users not currently viewing the webpage or connected to the internet. When they log on to the internet, they will receive notifications.

How to detect if a user is viewing your web page

In this section, you’ll learn how to detect active users on the chat page via theĀ Ā JavaScript Page visibility API. It allows us to track when a page is minimized, closed, open, and when a user switches to another tab.

Next, let’s use the API to send notifications to offline users.

Update theĀ sendNotificationĀ function to send the notification only when users are offline or on another tab.

function sendNotification(message, user) {
    document.onvisibilitychange = ()=> {
      if(document.hidden) {
        const notification = new Notification("New message from Open Chat", {
          icon: "https://cdn-icons-png.flaticon.com/512/733/733585.png",
          body: `@${user}: ${message}`
        })
        notification.onclick = ()=> function() {
          window.open("http://localhost:3000/chat")
        }
      }
    }  
}

From the code snippet above,Ā document.onvisibilitychangeĀ detects visibility changes, andĀ document.hiddenĀ checks if the user is on another tab or the browser is minimised before sending the notification. You can learn more about the different statesĀ here.

Next, update theĀ checkPageStatusĀ function to send notifications to all the users except the sender.

export default function checkPageStatus(message, user) {
  if(user !== localStorage.getItem("userName")) {
    if(!("Notification" in window)) {
      alert("This browser does not support system notifications!")
    } else if(Notification.permission === "granted") {
      sendNotification(message, user)
    }else if(Notification.permission !== "denied") {
       Notification.requestPermission((permission)=> {
          if (permission === "granted") {
            sendNotification(message, user)
          }
       })
    }
  }     
}

Congratulations!šŸŽ‰You can now send notifications to offline users.

Optional: How to save the messages to a JSON ā€œdatabaseā€ file

In this section, you’ll learn how to save the messages in a JSON file – for simplicity. Feel free to use any real-time database of your choice at this point, and you can continue reading if you are interested in learning how to use a JSON file as a database.

We’ll keep referencing theĀ server/index.jsĀ file for the remaining part of this article.

//index.js file
const express = require("express")
const app = express()
const cors = require("cors")
const http = require('http').Server(app);
const PORT = 4000
const socketIO = require('socket.io')(http, {
    cors: {
        origin: "http://localhost:3000"
    }
});

app.use(cors())
let users = []

socketIO.on('connection', (socket) => {
    console.log(`\u26a1: ${socket.id} user just connected!`)  
    socket.on("message", data => {
      console.log(data)
      socketIO.emit("messageResponse", data)
    })

    socket.on("typing", data => (
      socket.broadcast.emit("typingResponse", data)
    ))

    socket.on("newUser", data => {
      users.push(data)
      socketIO.emit("newUserResponse", users)
    })

    socket.on('disconnect', () => {
      console.log('\ud83d\udd25: A user disconnected');
      users = users.filter(user => user.socketID !== socket.id)
      socketIO.emit("newUserResponse", users)
      socket.disconnect()
    });
});

app.get("/api", (req, res) => {
  res.json({message: "Hello"})
});

http.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});

Retrieving messages from the JSON file

Navigate into the server folder and create aĀ messages.jsonĀ file.

cd server
touch messages.json

Add some default messages to the file by copying the code below – an array containing default messages.

{
   "messages":[
      {
         "text":"Hello!",
         "name":"nevodavid",
         "id":"abcd01"
      },
      {
         "text":"Welcome to my chat application!\ud83d\udc83\ud83c\udffb",
         "name":"nevodavid",
         "id":"defg02"
      },
      {
         "text":"You can start chatting!\ud83d\udcf2",
         "name":"nevodavid",
         "id":"hijk03"
      }
   ]
}

Import and read theĀ messages.jsonĀ file into theĀ server/index.jsĀ file by adding the code snippet below to the top of the file.

const fs = require('fs');
//Gets the messages.json file and parse the file into JavaScript object
const rawData = fs.readFileSync('messages.json');
const messagesData = JSON.parse(rawData);

Render the messages via the API route.

//Returns the JSON file
app.get('/api', (req, res) => {
  res.json(messagesData);
});

We can now fetch the messages on the client via theĀ ChatPageĀ component. The default messages are shown to every user when they sign in to the chat application.

import React, { useEffect, useState, useRef} from 'react'
import ChatBar from './ChatBar'
import ChatBody from './ChatBody'
import ChatFooter from './ChatFooter'

const ChatPage = ({socket}) => { 
  const [messages, setMessages] = useState([])
  const [typingStatus, setTypingStatus] = useState("")
  const lastMessageRef = useRef(null);

/**  Previous method via Socket.io */
  // useEffect(()=> {
  //   socket.on("messageResponse", data => setMessages([...messages, data]))
  // }, [socket, messages])

/** Fetching the messages from the API route*/
    useEffect(()=> {
      function fetchMessages() {
        fetch("http://localhost:4000/api")
        .then(response => response.json())
        .then(data => setMessages(data.messages))
      }
      fetchMessages()
  }, [])

 //....remaining code
}

export default ChatPage;

Saving messages to the JSON file

In the previous section, we created aĀ messages.jsonĀ file containing default messages and displayed the messages to the users.

Here, I’ll walk you through updating theĀ messages.jsonĀ file automatically after a user sends a message from the chat page.

Update the Socket.io message listener on the server to contain the code below:

socket.on("message", data => {
  messagesData["messages"].push(data)
  const stringData = JSON.stringify(messagesData, null, 2)
  fs.writeFile("messages.json", stringData, (err)=> {
    console.error(err)
  })
  socketIO.emit("messageResponse", data)
})

The code snippet above runs after a user sends a message. It adds the new data to the array in theĀ messages.jsonĀ file and rewrites it to contain the latest update.

Head back to the chat page, send a message, then reload the browser. Your message will be displayed. Open theĀ messages.jsonĀ file to view the updated file with the new entry.

Conclusion

In this article, you’ve learnt how to send desktop notifications to users, detect if a user is currently active on your page, and read and update a JSON file. These features can be used in different cases when building various applications.

This project is a demo of what you can build withĀ Socket.io; you can improve this application by adding authentication and connecting any database that supports real-time communication.

The source code for this tutorial is available here:https://github.com/novuhq/blog/tree/main/build-a-chat-app-part-two

Thank you for reading!

Read More

You’re five minutes away from your first Novu-backed notification

Create a free account, send your first notification, all before your coffee gets cold... no credit card required.