SSE Event Types and Data Format
You'll learn how to handle named events, parse incoming data, and understand the structure of Server-Sent Events messages.
When a server sends data through an SSE connection, it follows a specific text-based format. Think of it like sending labeled packages through a mail system—each message can have a type label, an ID tag, and the actual contents.
The SSE Message Format
SSE messages are plain text with special field names:
data:— The actual message content (required)event:— A custom event type name (optional, defaults to"message")id:— A unique identifier for reconnection (optional)retry:— Reconnection time in milliseconds (optional)
Each field starts at the beginning of a line, followed by a colon and the value. A blank line signals the end of a message.
Handling Named Events
By default, SSE messages trigger a "message" event. But servers can send custom event types:
const eventSource = new EventSource('/updates');
// Listen for default "message" events
eventSource.onmessage = (event) => {
console.log('Generic message:', event.data);
};
// Listen for custom "price-update" events
eventSource.addEventListener('price-update', (event) => {
console.log('Price changed:', event.data);
});
// Listen for custom "alert" events
eventSource.addEventListener('alert', (event) => {
console.log('Alert:', event.data);
});
Parsing Event Data
The event.data property contains the message as a string. If the server sends JSON, you'll need to parse it:
eventSource.addEventListener('user-joined', (event) => {
const userData = JSON.parse(event.data);
console.log(userData.name, 'joined the chat');
});
Key Takeaway: SSE messages use a simple text format with data: fields for content and optional event: names—use addEventListener() to handle custom event types and parse event.data as needed (often JSON).