">
 

How to Build a Reliable SSE Client in TypeScript

Iniciado por joomlamz, Hoje at 10:15

Respostas: 0   |   Visualizações: 2

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.


                     How to Build a Reliable SSE Client in TypeScript
               




Tópico:
                     How to Build a Reliable SSE Client in TypeScript
               
Categoria: Tutoriais | FreeCodeCamp Premium
Idioma Principal: Português (Conteúdo de Tecnologia)

Conteúdo do Tutorial / Guia Passo a Passo:
-------------------------------------------------------------------------
When you build a feature that streams data, like an AI chat response or a live notification feed, the network is rarely as cooperative as
fetchmakes it look.

Connections drop, proxies buffer responses, and mobile networks switch from WiFi to cellular mid-stream. If your streaming code doesn't plan for this, the user sees a response that just stops, with no error and no recovery.

In this article, you'll use an open source TypeScript library called Ore as a practical example of how to build a streaming client that handles real-world network conditions: automatic retries, the official Server-Sent Events (SSE) parsing spec, and clean integration with React and React Server Components.

By the end, you'll understand how async generators, the Fetch API, and the SSE spec fit together to build something far more reliable than a basic
fetchand
response.body.getReader()loop.

Table of Contents

• Prerequisites

• What You Will Learn

• What Is Server-Sent Events?

• Why Build a Custom Streaming Client?

• How to Stream Raw Chunks with an Async Generator

• How to Parse Server-Sent Events by Hand

• How to Implement Reconnection with Last-Event-ID

• How to Handle Retries with Backoff

• How to Use This with React

• How to Use This with React Server Components

• Conclusion

Prerequisites

To follow along, you should have:

• A working understanding of TypeScript

• Familiarity with
fetch,
ReadableStream, and
async/
await
• Basic knowledge of React (for the React-specific sections)

What You Will Learn

• How to stream raw text or bytes from a
fetchresponse using async generators

• How to parse the Server-Sent Events spec by hand, field by field

• How to implement automatic reconnection with
Last-Event-IDso you don't lose events

• How to handle retries with exponential backoff

• How to integrate a streaming client with React state and React Server Components

What Is Server-Sent Events?

Server-Sent Events (SSE) is a web standard for one-way streaming from server to client over a single HTTP connection. Unlike WebSockets, it's plain HTTP, which means it works through existing infrastructure like load balancers and proxies without special configuration.

An SSE response looks like this on the wire:

event: update
id: 42
data: {"status": "processing"}

event: update
id: 43
data: {"status": "complete"}

Each event is separated by a blank line. The
datafield carries the payload,
eventnames the event type, and
idlets the client track its position in the stream for reconnection.

The browser has a built-in
EventSourceAPI for this, but it has real limitations: no custom headers, no POST requests, and inconsistent reconnection behavior across browsers. For anything beyond the simplest case, you often need to parse the stream yourself.

Why Build a Custom Streaming Client?

Many streaming use cases, like AI chat responses, don't use the SSE spec at all. They're just raw chunks of text arriving over time. Other cases, like live notifications, genuinely benefit from the structure SSE provides: named events, IDs for resumption, and a server-controlled retry interval.

Ore handles both with two separate functions:


stream()
... [O tutorial continua no link abaixo] ...


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: