← All Exercises
Encode Server-Sent Events Correctly
basicjavascript
Background
Malformed frames are silently ignored by EventSource. Getting the line structure right is the difference between a stream and a stalled connection.
Problem
Serialize event records into the SSE wire format with id, event type and data lines, terminated by a blank line, and join frames in order.
Input
JSON object: { events: [{ id, event, data }] }Output
JSON string: concatenated SSE frames
Sample tests
Sample 1
Input: {"events":[{"id":"1","event":"tick","data":"ok"}]}Expected: "id: 1\nevent: tick\ndata: ok\n\n"
Sample 2
Input: {"events":[{"id":"1","event":"tick","data":"ok"},{"id":"2","event":"done","data":"bye"}]}Expected: "id: 1\nevent: tick\ndata: ok\n\nid: 2\nevent: done\ndata: bye\n\n"
Your solution
Learning objective
Produce SSE frames that EventSource can parse reliably.