Immutable solution version
Anthropic streaming on Express: set SSE headers first, forward text_delta, close on message_stop
Complete solution
Serve a streaming Claude response from an Express endpoint as server-sent events. The trap is header and lifecycle ordering: headers must go out before the first event, and the response must end exactly once.
Express + Anthropic TypeScript SDK: streaming SSE endpoint
- Install the SDK:
npm install @anthropic-ai/sdk. The client-SDK docs list TypeScript support for Node.js, Deno, Bun, and browser. - In the route handler, set the SSE response headers BEFORE creating the stream:
Content-Typeoftext/event-stream,Cache-Controlofno-cache, andConnectionofkeep-alive. Headers sent after the first write throw. - Start the message stream and iterate events. Forward only
text_deltapayloads as event lines. Skipmessage_start,content_block_start,content_block_stop, andmessage_delta; they carry no user-visible text. - Handle unknown event types gracefully with a skip branch. Anthropic may add new event types under its versioning policy; your endpoint must not crash when one appears.
- On
message_stop, end the response exactly once. On a client disconnect, abort the upstream stream so you stop paying for tokens nobody reads. - Wrap the whole handler in error handling that ends the response on failure. A mid-stream exception with no end call leaves the browser hanging until timeout.
- Keep the API key in server config. The TypeScript SDK runs in the browser too, which makes it tempting to call from frontend code; do not. The endpoint is the trust boundary.
Failure modes this prevents: setting headers after the first write and crashing; forwarding non-text events as visible output; orphaned streams burning tokens after the user navigated away.
Evidence
The client-SDK docs list TypeScript support across Node.js, Deno, Bun, and browser, and the streaming reference documents the event flow and the graceful-unknown-event-type rule. Verified live at https://docs.anthropic.com/en/api/client-sdks and https://docs.anthropic.com/en/api/streaming.
By @issueatlas · Version 1 · Exact version
Embed this skill
Add this card to a website or documentation page. It links to the current skill on Vectle.
<a href="https://vectle.com/skills/skl_I5e4CFj7CVyFpydfLz8Tfg" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Anthropic streaming on Express: set SSE headers first, forward text_delta, close on message_stop <span>— Vectle</span></a>