How to Stream AI Like ChatGPT in NestJS & React: 5 Steps
Learn how to stream AI responses word by word, just like ChatGPT, using Server-Sent Events in NestJS and React. A step-by-step guide with working code.

A complete, provider-agnostic architecture for real-time Server-Sent Events (SSE) token streaming, cancellation, and production hardening.
Streaming makes an AI feature feel fast even when the underlying model takes several seconds to finish: users see the first words in under a second instead of staring at a loading spinner for 10–20 seconds. That progressive, word-by-word "typing" effect is why modern AI assistants feel responsive - and you can build the exact same setup with NestJS and React in roughly 150 lines of code.
In this guide, you'll build a complete, provider-agnostic chat endpoint and frontend interface that streams tokens from any Large Language Model (LLM) to the browser as they're generated. You'll use:
NestJS for the backend API and streaming pipeline
Server-Sent Events (SSE) to push tokens to the client over standard HTTP
Any streaming LLM API or SDK wrapped behind a clean AsyncGenerator service
React with the native fetch API to incrementally parse and render the stream
By the end, you'll have a working, production-hardened implementation - complete with input validation, client disconnect cancellation, proxy heartbeats, error handling, and a Stop button.
How AI Streaming Works
LLMs generate text one token (a word or part of a word) at a time. Instead of holding the HTTP connection open until the entire answer finishes generating, the backend forwards each token to the browser the moment it is produced.
The request flows in five stages:
1. The React app sends the user's prompt to NestJS via a POST request.
2. NestJS flushes SSE response headers immediately and opens a streaming request to the LLM provider.
3. As each text delta arrives, NestJS writes it to the open HTTP response formatted as a Server-Sent Event.
4. React reads the response body chunk by chunk using a ReadableStream reader and appends each token to the UI.
5. When the model finishes, NestJS writes a final [DONE] event and closes the connection.
Why Server-Sent Events Instead of WebSockets?
Server-Sent Events provide a unidirectional stream from server to browser over plain HTTP. That matches the exact communication pattern of an AI response: the user sends one prompt, and the server streams back the answer. SSE works out of the box with standard HTTP authentication, load balancers, and reverse proxies—without introducing a second protocol, stateful connection tracking, or WebSocket scaling overhead you don't need here.
Why fetch instead of EventSource?
The browser's built-in EventSource API only supports GET requests and does not allow custom headers such as Authorization. Real chat prompts belong in a POST request body—both for security and because prompts (and multi-turn conversation histories) can easily exceed URL length limits. Using the SSE wire format on the server and reading it with fetch + ReadableStream on the client is the standard pattern production AI apps use.
Step 1: Set Up NestJS and a Provider-Agnostic AI Service
Start by creating a new NestJS project and installing @nestjs/config, class-validator, and class-transformer:
Add your provider credentials, base URL, and model name to a .env file in the root of ai-stream-api. Keeping the model identifier in environment configuration lets you upgrade or swap models without touching application code:
Next, create AiService to own all communication with your LLM provider. By exposing an AsyncGenerator<string> that yields plain text chunks, the rest of your application stays completely decoupled from any vendor-specific payload shape—switching providers later means editing only this one file.
Note: If you prefer an official provider SDK over raw fetch, keep the exact same async *streamChat(prompt: string, signal?: AbortSignal): AsyncGenerator<string> signature and yield each text chunk inside your loop.
Note: The request body above follows the OpenAI-compatible Chat Completions format. Some newer models expect max_completion_tokens instead of max_tokens, and token usage is only included in the stream if you add stream_options: { include_usage: true } to the body. Check your provider's docs for both.
Register AiService and ChatController inside src/ai/ai.module.ts:
Import ConfigModule.forRoot({ isGlobal: true }) and AiModule in src/app.module.ts:
Note: If your tsconfig.json uses "module": "nodenext" / "moduleResolution": "nodenext", keep .js extensions on relative imports such as './ai/ai.module.js'.
Finally, configure global DTO validation and CORS in src/main.ts so your React frontend can communicate with NestJS:
Step 2: Create a Streaming SSE Endpoint
NestJS includes a built-in @Sse() decorator, which is designed for GET routes that return an RxJS Observable and pair with browser EventSource clients. For a chat endpoint that takes a POST body, writing the SSE format directly to the Express Response object is simpler and gives you full control over headers and connection lifecycle events.
An SSE message is plain text: a data: line followed by a blank line (\n\n):
Encoding each token as JSON is crucial: generated tokens frequently contain newline characters (\n), which would prematurely split an SSE frame if sent as raw text.
First, create ChatDto with class-validator decorators to reject empty or oversized prompts before opening an LLM stream:
Next, create the controller skeleton in src/ai/chat.controller.ts with the required SSE headers:
What each header does:
Content-Type: text/event-stream tells browsers and proxies that the HTTP response is an ongoing event stream.
Cache-Control: no-cache, no-transform prevents caches and intermediaries from storing or compressing chunks.
Connection: keep-alive keeps the underlying HTTP connection open while tokens arrive.
X-Accel-Buffering: no tells reverse proxies like Nginx not to buffer the response. Without it, users wait until generation finishes and see the entire answer at once.
res.flushHeaders() sends the HTTP headers immediately so the stream opens before the first token arrives.
Using @Res() puts you directly in charge of the HTTP response, so NestJS will not attempt to serialize a return value automatically.
Step 3: Stream Tokens From the Model to the Client
Now replace // Streaming logic goes here (Step 3) in src/ai/chat.controller.ts with the complete streaming, disconnect-handling, and cleanup logic:
Here is what each piece does:
The for-await loop pulls text chunks from AiService.streamChat() as soon as the upstream model produces them and writes each chunk as data: {"text":"..."}\n\n.
res.on('close', handleDisconnect) detects premature browser disconnects. Propagating abortController.signal cancels the upstream LLM request immediately so you stop paying for tokens nobody will read. Listen on the response (res), not the request (req): in modern Node.js versions, req's close event fires as soon as the POST body finishes reading—before streaming even starts. Checking !res.writableFinished ensures normal completion isn't mistaken for an early disconnect.
The heartbeat writes an SSE comment (: ping) every 15 seconds so proxies don't close the connection while the model is thinking. It's cleared in finally so the timer always stops.
The [DONE] marker tells the client that generation finished normally, allowing React to distinguish a complete answer from a dropped network connection.
In-stream error events report failures inside the SSE payload. Because HTTP 200 status and headers were already flushed, you cannot switch to an HTTP 500 status mid-stream.
Logger records the real error on the server, while the user only sees a safe, generic message.
Verify the Endpoint From Your Terminal
Start your NestJS server (npm run start:dev) and verify streaming with curl. The -N (--no-buffer) flag disables curl's output buffering so tokens appear live:
You should see data: {"text":"..."} lines print incrementally one after another, ending with data: [DONE]. If the entire answer appears at once, check your headers and middleware before moving to React.
Step 4: Render the Stream Word by Word in React
Create a React + TypeScript frontend (for example with Vite: npm create vite@latest ai-stream-ui -- --template react-ts) and add VITE_API_URL=http://localhost:3000 to its .env file. On the frontend, separate the work into two clean modules: a stream-parsing utility and a UI component.
1. The Stream Reader (src/lib/streamChat.ts)
This function calls /chat/stream, reads the ReadableStream chunk by chunk, buffers incomplete SSE frames, and invokes onToken for every piece of text:
Why this buffer logic is essential:
Chunk boundaries do not match SSE boundaries: A single network chunk might contain half an event, or three events at once. Splitting on /\r?\n\r?\n/, holding back the trailing fragment in buffer, and flushing when the stream closes prevents JSON.parse errors.
Multi-byte UTF-8 safety: Passing { stream: true } to TextDecoder.decode() prevents multi-byte characters (such as emojis or non-Latin scripts) from corrupting if a character's bytes are split across two network packets.
Proxy resilience: parseEvent ignores SSE comment lines (such as : ping heartbeats), accepts data: with or without a space, and joins multi-line data: fields cleanly.
2. The Chat Component (src/components/Chat.tsx)
Two details make the frontend feel responsive:
setAnswer((prev) => prev + text) uses React's functional state updater so rapid tokens never overwrite each other between renders.
The cursor indicator (▍) signals active generation (pair it with a simple CSS @keyframes blink animation). To render rich Markdown (headings, code blocks, lists) instead of plain text, pass answer into a library like react-markdown.
Step 5: Make It Production-Ready
The setup above works reliably on localhost. Before deploying to production users and cloud infrastructure, address these real-world operational details.
1. Exclude SSE Routes From Compression Middleware
If your NestJS app uses compression middleware, it buffers outgoing bytes until enough data accumulates to compress efficiently—causing streamed tokens to arrive in delayed clumps. Skip compression for text/event-stream responses in src/main.ts:
2. Keep Connections Alive Through Proxies With Heartbeats
Load balancers, CDNs, and reverse proxies frequently drop HTTP connections that stay silent for 30–60 seconds, which can happen when a reasoning-heavy model pauses before its first token. The complete controller in Step 3 already handles this: it sends an SSE comment line (: ping) every 15 seconds, which SSE clients ignore, and clears the timer in finally whether the stream finishes, fails, or is cancelled.
If you deploy behind Nginx, also disable proxy buffering and extend the read timeout for your streaming route:
3. Production Security & Cost Checklist
Authentication: Protect /chat/stream with your auth guard (such as a JWT guard) and pass Authorization: Bearer <token> in the React fetch headers—something native EventSource cannot do.
Rate Limiting: Every LLM request incurs compute or API cost. Use @nestjs/throttler to cap requests per user/IP and enforce a max_tokens limit on model responses.
Input Limits: Validate prompt length with class-validator (@MaxLength(...)) so a single request cannot submit an unbounded, expensive prompt.
Conversation History: For multi-turn chat, send a bounded array of recent { role, content } messages rather than the entire conversation history to control latency and token usage.
Usage Tracking: Enable usage in the stream (for OpenAI-compatible APIs, add stream_options: { include_usage: true }), read it from the final chunk, and log it per user for quota enforcement or billing.
Never Expose API Keys: All upstream LLM calls must pass through your NestJS backend. Never bundle provider keys into your React app or VITE_ environment variables.
Common Mistakes to Avoid
Conclusion
Building ChatGPT-style AI streaming in NestJS and React comes down to a clean, modular pipeline:
1. Wrap your LLM provider behind an AsyncGenerator<string> in a NestJS service.
2. Open an SSE response on a POST endpoint with caching and buffering disabled.
3. Forward each text delta immediately and abort upstream generation when the client disconnects.
4. Read and buffer the ReadableStream in React with fetch and AbortController.
5. Harden production deployments with compression exclusions, proxy heartbeats, authentication, and rate limits.
Streaming doesn't make an LLM generate its full answer any faster, but delivering the first token in under a second transforms how responsive and interactive your entire product feels.
Frequently Asked Questions
Can I use NestJS's built-in @Sse() decorator instead?
Yes, if your endpoint can be a GET request. @Sse() routes return an RxJS Observable and pair with browser EventSource clients. For chat interfaces, a POST endpoint is usually preferable because prompts can be long and you'll often want to send an Authorization header.
How do I switch between different LLM providers?
Keep ChatController and your React frontend completely unchanged and update only AiService.streamChat(). Because streamChat() yields plain string tokens, swapping between any streaming LLM SDK or OpenAI-compatible API is isolated to a single file.
Should I use WebSockets instead of SSE for AI chat?
Usually not. AI text responses flow in one direction—from server to client—which is exactly what SSE is built for. WebSockets make more sense when both client and server continuously exchange real-time data simultaneously, such as live bidirectional voice or collaborative editing.
Why does my stream arrive all at once instead of incrementally?
An intermediary layer is buffering the response. Check three things: exclude text/event-stream from compression middleware, disable reverse-proxy buffering (X-Accel-Buffering: no and proxy_buffering off;), and verify that res.flushHeaders() runs before awaiting the upstream LLM stream.
How do I stop paying for tokens when a user closes the tab or clicks Stop?
Propagate an AbortSignal from res.on('close') on the backend into your upstream LLM request, and wire a frontend AbortController to your Stop button. When the client cancels or disconnects, the backend immediately aborts the upstream stream.
Sources
Systems that do not talk to each other?
Most of the cost in an integration project sits in the edge cases nobody documented. Send us the systems and the data that has to move between them.




