Week 19 • Day 1Week 19

Day 1:Web Frontend Fundamentals for AI Engineers & SSE Parsing

Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz

Day 1: Web Frontend Fundamentals for AI Engineers & SSE Parsing

1. First-Principles: EventSource vs. fetch(..., { body }) with ReadableStream

When building a modern AI Chatbot web interface, junior developers often attempt to use the browser's native new EventSource(url) API:

The Fatal Flaws of Traditional EventSource:

  1. HTTP GET Only: EventSource does NOT support HTTP POST request bodies. Sending large prompts, user histories, or attached logs via URL query parameters breaches browser URL length limits (2,048 chars) and leaks sensitive prompts into access logs!
  2. Missing Custom Headers: EventSource does not support adding custom Authorization: Bearer <token> or tenant headers in standard browser implementations.

2. Modern Standard: fetch() with ReadableStream

Modern production AI frontends (e.g. ChatGPT, Claude, Cursor) use standard fetch() with POST, consuming the response stream via response.body.getReader():

Architecture Flow Diagram
Browser as Web Browser (JS
Server as FastAPI ASGI Backend
>Server: POST /v1/chat/stream (JSON Payload
>Browser: HTTP 200 (Content-Type: text/event-stream
Stream Reading
>Browser: Byte chunks via TCP
>Browser: TextDecoder.decode() + Line-buffer split (\n\n
>Browser: Dispatch parsed event (thought, token, citation

The TCP Chunk Boundary Invariant

Because TCP is a stream protocol (not a message protocol), network packets can split an SSE frame right in the middle:

  • Packet 1: event: token\ndata: {"del
  • Packet 2: ta": "database"}\n\n A naive parser that attempts JSON.parse on every raw network chunk crashes with SyntaxError! A production client must implement a Line-Buffering Chunk Assembler.

In Simple English: Why Chat Apps Don't Use Old EventSource (fetch + ReadableStream)

Browser-native EventSource has 3 deal-breakers for modern AI apps:

  1. Supports ONLY HTTP GET (cannot send long chat message bodies via POST!).
  2. Cannot send custom Authorization: Bearer ... headers cleanly!
  3. Auto-reconnects on failure, silently re-triggering your LLM call and charging double money!

Production Standard (fetch + ReadableStream): Use standard POST with auth headers, read bytes via response.body.getReader(), and keep a leftover text buffer because network packets frequently slice a single JSON event right across two TCP chunks!