Membangun Sistem Notifikasi Realtime

Dipublikasikan: 12 Januari 2025 • Kategori: Developer • Penulis: Jumanto

Notifikasi realtime adalah fitur penting untuk aplikasi modern seperti marketplace, chat, transaksi online, dan dashboard admin. Pada artikel ini, kita membahas dua teknik populer: WebSocket dan Firebase Cloud Messaging (FCM).

1. Apa Itu Notifikasi Realtime?

Notifikasi realtime berarti informasi dikirim ke pengguna tanpa mereka harus melakukan refresh. Data dikirim secara langsung dari server ke client saat event terjadi.

2. Menggunakan WebSocket

WebSocket adalah teknologi yang memungkinkan komunikasi dua arah antara server dan client.

Contoh Server WebSocket (PHP Ratchet)


// server.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class NotifServer implements MessageComponentInterface {
    public function onMessage(ConnectionInterface $conn, $msg) {
        foreach ($conn->httpRequest->connections as $client) {
            $client->send($msg);
        }
    }
}

Client WebSocket (JavaScript)


const socket = new WebSocket("ws://localhost:8080");

socket.onmessage = function(event) {
    console.log("Notifikasi masuk:", event.data);
};

WebSocket cocok untuk:

3. Menggunakan Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging (FCM) adalah solusi paling mudah untuk push notification di Android, iOS, dan Web.

Contoh Mengirim Notifikasi FCM dengan PHP


$serverKey = "YOUR_FIREBASE_SERVER_KEY";
$token = "DEVICE_TOKEN";

$data = [
  "to" => $token,
  "notification" => [
    "title" => "Pesan Baru",
    "body"  => "Anda menerima pesan baru!"
  ]
];

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
  "Authorization: key=" . $serverKey,
  "Content-Type: application/json"
]);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl);
curl_close($curl);

Kelebihan FCM:

4. WebSocket vs Firebase

WebSocket Firebase
Realtime 100% live Tidak selalu live, tapi push notification cepat
Butuh server sendiri Tidak perlu server tambahan
Cocok untuk chat & dashboard Cocok untuk mobile notification

5. Best Practice Notifikasi Realtime

Dengan WebSocket atau Firebase, Anda dapat membangun sistem notifikasi yang cepat, aman, dan responsif untuk kebutuhan aplikasi modern.

← Kembali ke Blog