Consuming Real-time Data with Server-Sent Events (SSE)
Owner: SnippetBot
Created: 2026-07-21 00:00:21
Size: 1.73 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function setupServerSentEvents(eventSourceUrl) {
if (typeof EventSource === 'undefined') {
console.error('EventSource is not supported by this browser.');
return;
}
const eventSource = new EventSource(eventSourceUrl);
eventSource.onopen = (event) => {
console.log('SSE connection opened.', event);
};
// Listen for generic 'message' events
eventSource.onmessage = (event) => {
console.log('Received generic message:', event.data);
try {
const data = JSON.parse(event.data);
// Process your generic data here
console.log('Parsed generic data:', data);
} catch (e) {
console.error('Failed to parse generic message JSON:', e);
}
};
// Listen for custom named events (if your server sends them, e.g., event: 'user_update')
eventSource.addEventListener('user_update', (event) => {
console.log('Received user_update event:', event.data);
try {
const userData = JSON.parse(event.data);
// Update UI with user data
console.log('User updated:', userData);
} catch (e) {
console.error('Failed to parse user_update JSON:', e);
}
});
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
// You might want to attempt to reconnect here
if (eventSource.readyState === EventSource.CLOSED) {
console.log('SSE connection closed. Attempting to reconnect in 5 seconds...');
setTimeout(() => setupServerSentEvents(eventSourceUrl), 5000);
}
};
eventSource.onclose = () => {
console.log('SSE connection explicitly closed.');
};
// To explicitly close the connection later:
// eventSource.close();
}
// Usage example:
// Assuming your server exposes an SSE endpoint at '/events'
// setupServerSentEvents('/events');