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
Real-Time Notifications
Real-Time Notifications
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