{
    "slug": "js_eventsource",
    "term": "EventSource API — Server-Sent Events (Client Side)",
    "category": "javascript",
    "difficulty": "intermediate",
    "short": "EventSource is the browser API for consuming Server-Sent Events (SSE) — a one-directional server-to-client stream over HTTP that automatically reconnects, ideal for live feeds, notifications, and streaming LLM responses.",
    "long": "new EventSource(url) opens a persistent HTTP connection where the server pushes text/event-stream formatted messages. The browser automatically reconnects with exponential backoff if the connection drops, sending the Last-Event-ID header so the server can resume from where it left off. EventSource only supports GET requests and plain text — no binary, no custom headers without a polyfill. For bidirectional communication use WebSockets. For streaming responses from a PHP backend, the server writes 'data: <message>\\n\\n' and flushes — each double-newline is one event. Named events (event: type\\n) allow different listeners. SSE works through proxies better than WebSockets and requires no upgrade handshake.",
    "aliases": [
        "EventSource",
        "SSE client",
        "server-sent events JavaScript",
        "event stream"
    ],
    "tags": [
        "javascript",
        "sse",
        "streaming",
        "real-time",
        "http"
    ],
    "misconception": "EventSource and WebSockets are interchangeable. EventSource is server-to-client only and uses plain HTTP — simpler to deploy, works through proxies, auto-reconnects. WebSockets are bidirectional and require a persistent connection upgrade. Use SSE for push-only feeds; WebSockets when the client also needs to send real-time data.",
    "why_it_matters": "EventSource is the simplest way to stream real-time updates from a PHP backend — live order status, streaming AI responses, progress bars for long jobs. It requires no WebSocket server, works through standard HTTP infrastructure, and auto-reconnects without any application code.",
    "common_mistakes": [
        "Not disabling Nginx output buffering — Nginx buffers upstream responses by default; add 'X-Accel-Buffering: no' header or proxy_buffering off in nginx config.",
        "Forgetting the double newline to terminate events — each SSE message must end with \\n\\n; a single \\n continues the current event's data.",
        "Not handling the CORS case — EventSource sends credentials by default only to same-origin; for cross-origin, pass { withCredentials: true } and set appropriate CORS headers.",
        "Long-lived PHP scripts without max_execution_time override — SSE streams run indefinitely; set set_time_limit(0) at the start of the streaming script.",
        "Not closing EventSource when navigating away — forgetting to call es.close() leaves connections open on the server; attach cleanup to beforeunload or component unmount."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "js_fetch_api",
        "js_streams_api",
        "long_polling_sse",
        "websockets",
        "llm_streaming"
    ],
    "prerequisites": [],
    "refs": [
        "https://developer.mozilla.org/en-US/docs/Web/API/EventSource"
    ],
    "bad_code": "// ❌ Polling — inefficient, delayed, hammers the server\nsetInterval(async () => {\n    const res  = await fetch('/api/notifications');\n    const data = await res.json();\n    if (data.length) showNotifications(data);\n}, 3000); // New HTTP request every 3 seconds even when nothing changed",
    "good_code": "// ✅ EventSource — persistent connection, server pushes when ready\nconst es = new EventSource('/api/notifications/stream');\n\nes.onmessage = (event) => {\n    const notification = JSON.parse(event.data);\n    showNotification(notification);\n};\n\n// Named events — different handlers per event type\nes.addEventListener('order-shipped', (event) => {\n    updateOrderStatus(JSON.parse(event.data));\n});\n\nes.onerror = (err) => {\n    // Browser auto-reconnects — this fires on reconnect attempts too\n    if (es.readyState === EventSource.CLOSED) {\n        console.error('SSE connection permanently closed');\n    }\n};\n\n// Close when done (e.g. user navigates away)\nwindow.addEventListener('beforeunload', () => es.close());\n\n// PHP side:\n// header('Content-Type: text/event-stream');\n// header('Cache-Control: no-cache');\n// header('X-Accel-Buffering: no'); // Nginx: disable buffering\n// while (true) {\n//     echo 'data: ' . json_encode(getLatestEvent()) . \"\\n\\n\";\n//     ob_flush(); flush();\n//     sleep(1);\n// }",
    "quick_fix": "For a PHP streaming endpoint, set header('Content-Type: text/event-stream') and echo 'data: ' . $message . \"\\n\\n\" with ob_flush() + flush() in a loop. On the client, new EventSource('/stream').onmessage = e => console.log(e.data).",
    "effort": "low",
    "created": "2026-03-23",
    "updated": "2026-05-02",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/js_eventsource",
        "html_url": "https://codeclaritylab.com/glossary/js_eventsource",
        "json_url": "https://codeclaritylab.com/glossary/js_eventsource.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[EventSource API — Server-Sent Events (Client Side)](https://codeclaritylab.com/glossary/js_eventsource) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/js_eventsource"
            }
        }
    }
}