Sistem notifikasi real-time sudah menjadi fitur wajib dalam aplikasi modern. Bayangkan harus refresh terus untuk lihat notifikasi baru - tidak efisien, kan? Nah, WebSocket hadir sebagai solusi untuk membuat sistem notifikasi yang instant dan efisien. Mari kita pelajari cara membuatnya!
Apa itu WebSocket?
WebSocket adalah protokol komunikasi dua arah yang memungkinkan pertukaran data real-time antara client dan server. Berbeda dengan HTTP yang bersifat request-response, WebSocket membuat koneksi tetap terbuka untuk komunikasi yang lebih efisien.
1. Persiapan Project
Backend (Node.js dengan Socket.io)
Pertama, kita siapkan project Node.js dan install dependencies yang diperlukan:
npm init -y npm install express socket.io cors
Buat file server.js:
const express = require('express'); const app = express(); const http = require('http').createServer(app); const io = require('socket.io')(http, { cors: { origin: "http://localhost:3000", methods: ["GET", "POST"] } }); io.on('connection', (socket) => { console.log('User connected:', socket.id); socket.on('join-room', (userId) => { socket.join(userId); console.log(`User ${socket.id} joined room ${userId}`); }); socket.on('send-notification', (data) => { io.to(data.userId).emit('receive-notification', { title: data.title, message: data.message, timestamp: new Date() }); }); socket.on('disconnect', () => { console.log('User disconnected:', socket.id); }); }); http.listen(5000, () => { console.log('Server running on port 5000'); });
Frontend (React)
Untuk frontend, kita akan menggunakan React dengan Socket.io-client:
npm create vite@latest notification-app -- --template react cd notification-app npm install socket.io-client @heroicons/react
2. Implementasi Komponen Notifikasi
Buat file NotificationComponent.jsx:
import React, { useEffect, useState } from 'react'; import io from 'socket.io-client'; const socket = io('http://localhost:5000'); const NotificationComponent = ({ userId }) => { const [notifications, setNotifications] = useState([]); useEffect(() => { // Join room berdasarkan userId socket.emit('join-room', userId); // Listen untuk notifikasi baru socket.on('receive-notification', (notification) => { setNotifications(prev => [...prev, notification]); }); return () => { socket.off('receive-notification'); }; }, [userId]); return ({notifications.map((notif, index) => (); }; export default NotificationComponent;))}{notif.title}
{notif.message}
{new Date(notif.timestamp).toLocaleTimeString()}
3. Mengirim Notifikasi
Contoh komponen untuk mengirim notifikasi:
const SendNotification = ({ userId }) => { const handleSendNotification = () => { socket.emit('send-notification', { userId: userId, title: 'Notifikasi Baru', message: 'Ini adalah pesan notifikasi test' }); }; return ( ); };
Best Practices
- Selalu handle reconnection untuk koneksi yang terputus
- Implementasikan error handling yang baik
- Gunakan room untuk mengoptimalkan pengiriman notifikasi
- Batasi jumlah notifikasi yang ditampilkan
4. Optimasi Performa
Batasi Jumlah Koneksi
Tambahkan kode berikut di server untuk membatasi jumlah koneksi:
io.use((socket, next) => { const clientsCount = io.sockets.sockets.size; if (clientsCount > 1000) { next(new Error('Terlalu banyak koneksi')); return; } next(); });
Implementasi Queue
Untuk menangani traffic tinggi, implementasikan sistem queue:
const Queue = require('bull'); const notificationQueue = new Queue('notifications'); notificationQueue.process(async (job) => { const { userId, notification } = job.data; io.to(userId).emit('receive-notification', notification); });
5. Keamanan
Implementasi middleware autentikasi:
io.use((socket, next) => { const token = socket.handshake.auth.token; if (isValidToken(token)) { socket.user = getUserFromToken(token); next(); } else { next(new Error('Authentication error')); } });
Tips Keamanan
- Selalu validasi data yang diterima dari client
- Gunakan HTTPS untuk koneksi WebSocket
- Implementasikan rate limiting
- Enkripsi data sensitif
6. Testing
Contoh test menggunakan Jest:
describe('WebSocket Notification Tests', () => { let clientSocket; beforeAll((done) => { clientSocket = io('http://localhost:5000'); clientSocket.on('connect', done); }); test('should receive notification', (done) => { clientSocket.on('receive-notification', (data) => { expect(data).toHaveProperty('title'); expect(data).toHaveProperty('message'); done(); }); clientSocket.emit('send-notification', { userId: 'test-user', title: 'Test Notification', message: 'Test Message' }); }); });
Kesimpulan
Implementasi sistem notifikasi real-time dengan WebSocket memberikan pengalaman pengguna yang lebih baik dengan update instan tanpa perlu refresh halaman. Dengan mengikuti panduan ini, Anda dapat membuat sistem notifikasi yang scalable dan efisien.
Seperti halnya sistem notifikasi yang perlu monitoring berkelanjutan, domain website Anda juga membutuhkan pemantauan rutin. Untuk informasi lengkap tentang monitoring domain expired, list domain expired, dan marketplace domain terpercaya, kunjungi Back.co.id.
Langkah Selanjutnya
- Implementasikan sistem notifikasi offline
- Tambahkan fitur read/unread status
- Integrasikan dengan push notifications
- Buat sistem analytics untuk monitoring