How to Implement Real-Time Notifications in Magento 2

Why Real-Time Notifications Matter in Magento 2
Imagine a customer places an order on your Magento 2 store, but you don’t get notified immediately. Or worse, your admin team misses a critical update because the notification system is slow. That’s where real-time notifications come in—they keep everyone in the loop instantly, improving efficiency and customer satisfaction.
In this post, we’ll walk through how to implement real-time notifications in Magento 2, step by step. Whether you’re a developer or a store owner looking to enhance your site, this guide will help you get it done smoothly.
Understanding Real-Time Notifications
Real-time notifications are alerts that appear instantly when an event occurs—like a new order, customer inquiry, or inventory update. Unlike traditional email notifications, which can be delayed, real-time notifications use technologies like WebSockets or server-sent events (SSE) to push updates to users immediately.
In Magento 2, you can implement these notifications in several ways:
- Frontend Notifications – Display alerts to customers (e.g., order confirmations, stock updates).
- Admin Notifications – Alert store managers about new orders, customer messages, or system issues.
- Custom Event-Based Alerts – Trigger notifications for specific actions (e.g., low stock, abandoned cart).
Step 1: Setting Up WebSockets for Real-Time Communication
WebSockets enable a persistent connection between the server and client, allowing instant data transfer. Here’s how to integrate them into Magento 2:
1. Install a WebSocket Server
You can use Node.js with the ws
library or PHP-based solutions like Ratchet. Here’s a basic Node.js setup:
// server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
console.log('WebSocket server running on ws://localhost:8080');
Run this with node server.js
.
2. Connect Magento 2 to the WebSocket Server
Add this JavaScript to your Magento 2 theme:
// Connect to WebSocket
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
console.log('Connected to WebSocket server');
};
socket.onmessage = (event) => {
const notification = JSON.parse(event.data);
// Display notification (we'll cover this later)
showNotification(notification);
};
Step 2: Triggering Notifications from Magento 2 Events
Magento 2’s event system makes it easy to dispatch notifications when something happens. Let’s create a custom observer for new orders.
1. Create an Observer
In your custom module’s etc/events.xml
:
<event name="sales_order_place_after">
<observer name="magefine_realtime_notify_order" instance="Magefine\RealtimeNotifications\Observer\NewOrderObserver"/>
</event>
2. Define the Observer Logic
In Observer/NewOrderObserver.php
:
<?php
namespace Magefine\RealtimeNotifications\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\HTTP\Client\Curl;
class NewOrderObserver implements ObserverInterface
{
protected $curl;
public function __construct(Curl $curl) {
$this->curl = $curl;
}
public function execute(Observer $observer) {
$order = $observer->getEvent()->getOrder();
$data = [
'type' => 'new_order',
'message' => "New Order #{$order->getIncrementId()}",
'order_id' => $order->getId()
];
// Send to WebSocket server
$this->curl->post('http://localhost:8080/broadcast', json_encode($data));
}
}
Step 3: Displaying Notifications on the Frontend
Now, let’s show these notifications to users. We’ll use a simple toast notification system.
1. Add Notification UI
Include this CSS and HTML in your theme:
<div id="notification-container" style="position: fixed; bottom: 20px; right: 20px; z-index: 9999;"></div>
<script>
function showNotification(data) {
const container = document.getElementById('notification-container');
const notification = document.createElement('div');
notification.className = 'notification';
notification.innerHTML = `
<div style="background: #4CAF50; color: white; padding: 15px; margin: 5px; border-radius: 4px;">
${data.message}
</div>
`;
container.appendChild(notification);
setTimeout(() => notification.remove(), 5000);
}
</script>
Step 4: Admin Notifications (For Backend Users)
To notify admin users, we’ll use Magento’s built-in notification system with real-time updates.
1. Create a Custom Admin Notification Feed
In etc/adminhtml/di.xml
:
<type name="Magento\AdminNotification\Model\Feed">
<plugin name="magefine_realtime_admin_notifications" type="Magefine\RealtimeNotifications\Plugin\AdminNotificationFeed"/>
</type>
2. Modify the Feed to Include Real-Time Alerts
<?php
namespace Magefine\RealtimeNotifications\Plugin;
class AdminNotificationFeed
{
public function afterGetFeedData(\Magento\AdminNotification\Model\Feed $subject, $result) {
// Fetch real-time alerts from WebSocket
$realTimeAlerts = $this->getRealTimeAlerts();
return array_merge($result, $realTimeAlerts);
}
protected function getRealTimeAlerts() {
// In a real implementation, fetch from WebSocket
return [
[
'severity' => 'critical',
'title' => 'New Order Placed',
'description' => 'A customer just placed an order!'
]
];
}
}
Step 5: Testing & Debugging
Before going live, test your implementation:
- Place a test order – verify the notification appears.
- Check admin notifications – ensure alerts show up.
- Monitor WebSocket connections – confirm stability.
Use browser developer tools (F12 → Network → WS) to debug WebSocket connections.
Final Thoughts
Real-time notifications can transform your Magento 2 store by keeping everyone informed instantly. Whether it’s new orders, customer messages, or inventory alerts, this setup ensures no critical update goes unnoticed.
Need a ready-made solution? Check out Magefine’s extensions for pre-built notification systems that save you development time!
Got questions? Drop them in the comments below!