Server-Sent Events with EventSource
Quick answer
EventSource receives a stream of text events over HTTP. It suits server-to-client notifications when the client does not need a two-way socket.
How it works
The server returns text/event-stream encoded as UTF-8. Fields include data, event, id and retry. A blank line dispatches the assembled event; multiple data lines are joined with a newline. Without event, the event type is message. Named events require matching listeners. EventSource reconnects after eligible failures and can send Last-Event-ID when reconnecting; replay and deduplication are application responsibilities. close() stops this instance. Sending data to the server uses a separate request. Cross-origin connections follow CORS; withCredentials enables credentialed requests when supported by server policy.
Local examples
Run in the isolated projects/realtime-lab development origin (see README). NOT RUN in local validation; expected result is instructional.
(async () => {const es=new EventSource("/events");try{const event=await new Promise((ok,no)=>{es.addEventListener("update",ok,{once:true});es.onerror=()=>no(new Error("stream failed"));});console.log(event.lastEventId,event.data);}finally{es.close();}})()Expected console output (not executed locally):
1 readyThe lab emits a named update with id 1 and text ready.
Run in the isolated projects/realtime-lab development origin (see README). NOT RUN in local validation; expected result is instructional.
(async () => {const es=new EventSource("/events");es.close();console.log(es.readyState===EventSource.CLOSED);})()Expected console output (not executed locally):
trueClosing immediately sets CLOSED without waiting for the server. The fixture is reserved for the lab origin.
Common mistakes
Do not use EventSource to send client messages or assume reconnect guarantees exactly-once delivery. Close it when the view is disposed.
Practice
Connect to the lab events endpoint, record a named update and its ID, then close the connection after one message.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Server-Sent Events with EventSource — Knowledge Check
Apply the concept and reason about local example output.
What is the media type for an SSE response?
How do two data lines in one SSE event combine?
How can a client send an action when it receives SSE updates?
What is the expected console output of Server-Sent Events with EventSource example 1?
(async () => {const es=new EventSource("/events");try{const event=await new Promise((ok,no)=>{es.addEventListener("update",ok,{once:true});es.onerror=()=>no(new Error("stream failed"));});console.log(event.lastEventId,event.data);}finally{es.close();}})()What is the expected console output of Server-Sent Events with EventSource example 2?
(async () => {const es=new EventSource("/events");es.close();console.log(es.readyState===EventSource.CLOSED);})()