DEV Community

Cover image for Building Real-Time Notifications in a Node.js App Using WebSockets
HexShift
HexShift

Posted on

1 1 1

Building Real-Time Notifications in a Node.js App Using WebSockets

Building Real-Time Notifications in a Node.js App Using WebSockets

Adding real-time capabilities like notifications is one of the best ways to enhance interactivity in modern web applications. In this guide, we’ll walk through building a basic real-time notification system using Node.js, Socket.IO, and Express.

Why Use WebSockets?

WebSockets provide a persistent connection between the client and server, enabling real-time bidirectional communication. This makes them ideal for notifications, chats, collaborative editing, and live data feeds.

Step 1: Set Up the Server

npm init -y
npm install express socket.io

Then create server.js:

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: '*',
  }
});

app.get('/', (req, res) => {
  res.send('Server is running');
});

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  socket.on('send-notification', (data) => {
    io.emit('receive-notification', data);
  });

  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Step 2: Set Up the Client

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Real-Time Notifications</title>
  <script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
</head>
<body>
  <h1>Real-Time Notifications</h1>
  <button onclick="sendNotification()">Send Notification</button>
  <ul id="notifications"></ul>

  <script>
    const socket = io('http://localhost:3000');

    socket.on('receive-notification', (data) => {
      const li = document.createElement('li');
      li.textContent = data.message;
      document.getElementById('notifications').appendChild(li);
    });

    function sendNotification() {
      socket.emit('send-notification', { message: 'New notification sent!' });
    }
  </script>
</body>
</html>

Step 3: Customize and Expand

  • Add authentication and associate sockets with users.
  • Save notifications to a database for offline users.
  • Use namespaces or rooms to target specific users.
  • Use libraries like Redis to scale across multiple Node instances.

Conclusion

Real-time features like notifications add a modern, dynamic touch to web apps. With Node.js and Socket.IO, you can build a solid foundation for more complex real-time systems like messaging, presence indicators, or collaborative tools.

If you found this helpful, consider supporting me: buymeacoffee.com/hexshift

Postmark Image

20% off for developers who'd rather build features than debug email

Stop wrestling with email delivery and get back to the code you love. Postmark handles the complexities of email infrastructure so you can ship your product faster.

Start free

Top comments (0)