An open API service indexing awesome lists of open source software.

https://github.com/ndamulelonemakh/nextjs-react-sse-starter

A demonstration of Server-Sent Events (SSE) streaming between a Next.js React frontend and FastAPI Python backend.
https://github.com/ndamulelonemakh/nextjs-react-sse-starter

eventsource-api fastapi nextjs sse streaming

Last synced: about 1 month ago
JSON representation

A demonstration of Server-Sent Events (SSE) streaming between a Next.js React frontend and FastAPI Python backend.

Awesome Lists containing this project

README

          

# NextJS React SSE FastAPI Demo

A demonstration of Server-Sent Events (SSE) streaming between a Next.js React frontend and FastAPI Python backend. This repo shows how to implement, customize, and optimize real-time streaming for AI.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fndamulelonemakh%2Fnextjs-react-sse-starter&env=OPENAI_API_KEY&envDescription=API%20keys%20needed%20for%20application&project-name=nextjs-react-sse-starter&repository-name=nextjs-react-sse-starter)

## ๐Ÿš€ Key Features

- **Raw SSE Protocol Exploration**: See exactly how SSE works under the hood
- **Custom Streaming Protocols**: Create your own message formats and event types
- **Function Calling**: Demonstrate tool/function calling during streaming
- **Interactive Debug Console**: Visualize and inspect every streaming event

## โœจ Why Server-Sent Events?

Server-Sent Events (SSE) provide a simple, efficient way for servers to push data to clients over a single HTTP connection. Unlike WebSockets, SSE:

- Only flows in one direction (server โ†’ client)
- Uses standard HTTP, not a separate protocol
- Has built-in reconnection handling
- Works through most firewalls and proxies
- Has native browser support via the EventSource API

This makes SSE ideal for real-time updates like notifications, data feeds, andโ€”as shown in this demoโ€”streaming AI responses.

## ๐Ÿ› ๏ธ Project Structure

```
/
โ”œโ”€โ”€ api/ # FastAPI backend
โ”‚ โ”œโ”€โ”€ index.py # Main API with streaming endpoints
โ”‚ โ””โ”€โ”€ utils/ # Helper functions and tools
โ”œโ”€โ”€ app/ # Next.js pages
โ”‚ โ”œโ”€โ”€ debug/ # Raw stream debug console
โ”‚ โ””โ”€โ”€ page.tsx # Custom protocol demo
โ”œโ”€โ”€ components/ # React components
```

## ๐Ÿ”ฎ Streaming Protocol Examples

This demo showcases multiple approaches to streaming protocols:

### 1. Vercel AI SDK Protocol

The original Vercel AI SDK protocol uses numeric and alphabetic prefixes:

```
0:{"Hello"} # Content token
9:{"toolCallId":"123"} # Function call
a:{"result":"data"} # Function result
e:{"finishReason":"stop"} # End of stream
```

### 2. Custom Semantic Protocol

A more readable custom protocol with meaningful prefixes:

```
TEXT: "Hello there" # Content token
FUNC: {"name":"get_weather"} # Function call
RESP: {"result":{"temp":72}} # Function result
META: {"tokens":45} # Stream metadata
DEBUG: {"event":"stream_start"} # Debug information
```

## ๐Ÿ”„ SSE Limitations & Best Practices

- **Connection Limits**: Browsers typically limit to 6 connections per domain in HTTP/1.1
- **Message Size**: No official size limit, but best to send many small messages
- **Timeouts**: Use heartbeat messages to keep connections alive
- **Binary Data**: SSE is text-only (UTF-8); binary data must be encoded
- **Reconnection**: Implement proper reconnection strategies for reliability

## ๐Ÿ“š Advanced Features

### Microsoft SSE Client Library

For production applications, consider using [microsoft/fetch-event-source](https://github.com/microsoft/fetch-event-source), which provides:

```javascript
// Usage example:
import { fetchEventSource } from "@microsoft/fetch-event-source";

fetchEventSource("/api/stream", {
onmessage(event) {
console.log(event.data);
},
onerror(err) {},
onclose() {},
openWhenHidden: true,
// Many more options!
});
```

## ๐Ÿš€ Getting Started

To run the example locally you need to:

1. Clone the repository
2. Install dependencies:
```bash
pnpm install
pip install -r requirements.txt
```
3. Create `.env.local` with your OpenAI API key:
```
OPENAI_API_KEY=your_key_here
```
4. Run the development server:
```bash
pnpm run dev
```
5. Open [http://localhost:3000](http://localhost:3000)

## ๐Ÿ“Š Demo Pages

- **/**: Custom streaming protocol demo (main page)
- **/debug**: Raw SSE protocol visualization

## ๏ฟฝ Acknowledgments

This project was inspired by the work from the Vercel team on [ai-sdk-preview-python-streaming](https://github.com/vercel-labs/ai-sdk-preview-python-streaming). We've built upon their foundation to create an updated version of NextJS and more explicit handling of events to demonstate a `behind-the-scenes` look at how SSE works.

## ๏ฟฝ๐Ÿ“„ License

MIT