Rorix Technologies
Engineering18 min read

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.

NestJSReactTypeScriptServer-Sent EventsAI StreamingLLMNode.jsWeb DevelopmentEngineeringAI IntegrationAIArtificial Intelligence
How to Stream AI Like ChatGPT in NestJS & React: 5 Steps

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:

Terminal
npx @nestjs/cli new ai-stream-api
cd ai-stream-api
npm install @nestjs/config class-validator 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:

.env
AI_API_KEY=your-api-key-here
AI_BASE_URL=https://api.example.com/v1
AI_MODEL=your-preferred-streaming-model
PORT=3000

 

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.

TypeScript — src/ai/ai.service.ts
// src/ai/ai.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AiService {
  private readonly apiKey: string;
  private readonly baseUrl: string;
  private readonly model: string;

  constructor(config: ConfigService) {
    this.apiKey = config.getOrThrow<string>('AI_API_KEY');
    this.baseUrl = config.getOrThrow<string>('AI_BASE_URL');
    this.model = config.getOrThrow<string>('AI_MODEL');
  }

  async *streamChat(
    prompt: string,
    signal?: AbortSignal,
  ): AsyncGenerator<string> {
    const response = await fetch(`${this.baseUrl}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify({
        model: this.model,
        max_tokens: 1024,
        messages: [{ role: 'user', content: prompt }],
        stream: true,
      }),
      signal,
    });

    if (!response.ok || !response.body) {
      throw new Error(`LLM provider returned status ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const events = buffer.split(/\r?\n\r?\n/);
        buffer = events.pop() ?? '';

        for (const event of events) {
          for (const line of event.split(/\r?\n/)) {
            if (!line.startsWith('data:')) continue;
            const payload = line.slice(5).trim();
            if (payload === '[DONE]') return;

            const parsed = JSON.parse(payload);
            const delta: string | undefined =
              parsed.choices?.[0]?.delta?.content;

            if (delta) {
              yield delta;
            }
          }
        }
      }
    } finally {
      // Closes the upstream connection if the loop exits early
      await reader.cancel().catch(() => undefined);
    }
  }
}

 

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:

TypeScript — src/ai/ai.module.ts
// src/ai/ai.module.ts
import { Module } from '@nestjs/common';
import { AiService } from './ai.service';
import { ChatController } from './chat.controller';

@Module({
  providers: [AiService],
  controllers: [ChatController],
})
export class AiModule {}

 

Import ConfigModule.forRoot({ isGlobal: true }) and AiModule in src/app.module.ts:

TypeScript — src/app.module.ts
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AiModule } from './ai/ai.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    AiModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

 

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:

TypeScript — src/main.ts
// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
    }),
  );

  app.enableCors({
    origin: 'http://localhost:5173',
  });

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

 

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):

SSE Wire Format
data: {"text":"Hello"}

data: {"text":" world"}

 

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:

TypeScript — src/ai/dto/chat.dto.ts
// src/ai/dto/chat.dto.ts
import { IsNotEmpty, IsString, MaxLength } from 'class-validator';

export class ChatDto {
  @IsString()
  @IsNotEmpty()
  @MaxLength(4000)
  prompt: string;
}

 

Next, create the controller skeleton in src/ai/chat.controller.ts with the required SSE headers:

TypeScript — src/ai/chat.controller.ts (Headers)
// src/ai/chat.controller.ts
import { Body, Controller, Post, Res } from '@nestjs/common';
import type { Response } from 'express';
import { AiService } from './ai.service';
import { ChatDto } from './dto/chat.dto';

@Controller('chat')
export class ChatController {
  constructor(private readonly ai: AiService) {}

  @Post('stream')
  async stream(@Body() body: ChatDto, @Res() res: Response) {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache, no-transform');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Accel-Buffering', 'no');
    res.flushHeaders();

    const send = (data: unknown) => {
      if (!res.destroyed && !res.writableEnded) {
        res.write(`data: ${JSON.stringify(data)}\n\n`);
      }
    };

    // Streaming logic goes here (Step 3)
  }
}

 

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:

TypeScript — src/ai/chat.controller.ts (Complete)
// src/ai/chat.controller.ts
import { Body, Controller, Logger, Post, Res } from '@nestjs/common';
import type { Response } from 'express';
import { AiService } from './ai.service';
import { ChatDto } from './dto/chat.dto';

@Controller('chat')
export class ChatController {
  private readonly logger = new Logger(ChatController.name);

  constructor(private readonly ai: AiService) {}

  @Post('stream')
  async stream(@Body() body: ChatDto, @Res() res: Response) {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache, no-transform');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Accel-Buffering', 'no');
    res.flushHeaders();

    // Keep proxies from closing a silent connection (see Step 5)
    const heartbeat = setInterval(() => {
      if (!res.destroyed && !res.writableEnded) {
        res.write(': ping\n\n');
      }
    }, 15_000);

    const abortController = new AbortController();

    // If the user closes the tab or clicks Stop, abort the upstream LLM request
    const handleDisconnect = () => {
      if (!res.writableFinished && !res.writableEnded) {
        abortController.abort();
      }
    };

    res.on('close', handleDisconnect);

    const send = (data: unknown) => {
      if (
        !abortController.signal.aborted &&
        !res.destroyed &&
        !res.writableEnded
      ) {
        res.write(`data: ${JSON.stringify(data)}\n\n`);
      }
    };

    try {
      for await (const text of this.ai.streamChat(
        body.prompt,
        abortController.signal,
      )) {
        if (abortController.signal.aborted) break;
        send({ text });
      }

      if (!abortController.signal.aborted) {
        res.write('data: [DONE]\n\n');
      }
    } catch (err) {
      if (!abortController.signal.aborted) {
        this.logger.error('AI stream failed', err instanceof Error ? err.stack : err);
        send({ error: 'The AI service failed. Please try again.' });
      }
    } finally {
      clearInterval(heartbeat);
      res.off('close', handleDisconnect);
      if (!res.destroyed && !res.writableEnded) {
        res.end();
      }
    }
  }
}

 

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:

Terminal
curl -N -X POST http://localhost:3000/chat/stream \
  -H "Content-Type: application/json" \
  -d '{"prompt":"Explain SSE in three sentences"}'

 

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:

TypeScript — src/lib/streamChat.ts
// src/lib/streamChat.ts
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';

// Returns an event's data payload, or null for comments and empty frames
function parseEvent(raw: string): string | null {
  const dataLines = raw
    .split(/\r?\n/)
    .filter((line) => line.startsWith('data:'))
    .map((line) => line.slice(5).replace(/^ /, ''));

  return dataLines.length > 0 ? dataLines.join('\n') : null;
}

export async function streamChat(
  prompt: string,
  onToken: (text: string) => void,
  signal: AbortSignal,
): Promise<void> {
  const res = await fetch(`${API_URL}/chat/stream`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ prompt }),
    signal,
  });

  if (!res.ok || !res.body) {
    throw new Error(`Request failed with status ${res.status}`);
  }

  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  // Handles one complete event; returns true when [DONE] is received
  const handle = (raw: string): boolean => {
    const data = parseEvent(raw);
    if (data === null) return false;
    if (data === '[DONE]') return true;

    const parsed = JSON.parse(data);
    if (parsed.error) throw new Error(parsed.error);
    if (parsed.text) onToken(parsed.text);
    return false;
  };

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const events = buffer.split(/\r?\n\r?\n/);
      buffer = events.pop() ?? ''; // Retain any incomplete event for the next chunk

      for (const event of events) {
        if (handle(event)) return;
      }
    }

    // Flush anything left in the buffer once the connection closes
    buffer += decoder.decode();
    if (buffer.trim() && handle(buffer)) return;

    throw new Error('The connection closed before the answer finished.');
  } finally {
    reader.releaseLock();
  }
}

 

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)

TSX — src/components/Chat.tsx
// src/components/Chat.tsx
import { useRef, useState } from 'react';
import { streamChat } from '../lib/streamChat';

export function Chat() {
  const [prompt, setPrompt] = useState('');
  const [answer, setAnswer] = useState('');
  const [error, setError] = useState('');
  const [isStreaming, setIsStreaming] = useState(false);
  const controllerRef = useRef<AbortController | null>(null);

  async function handleSend() {
    if (!prompt.trim() || isStreaming) return;

    const controller = new AbortController();
    controllerRef.current = controller;
    setAnswer('');
    setError('');
    setIsStreaming(true);

    try {
      await streamChat(
        prompt,
        (text) => setAnswer((prev) => prev + text),
        controller.signal,
      );
    } catch (err) {
      if (!controller.signal.aborted) {
        setError(err instanceof Error ? err.message : 'Something went wrong.');
      }
    } finally {
      if (controllerRef.current === controller) {
        controllerRef.current = null;
        setIsStreaming(false);
      }
    }
  }

  return (
    <div className="chat">
      <textarea
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)}
        placeholder="Ask anything..."
        rows={4}
      />

      {isStreaming ? (
        <button onClick={() => controllerRef.current?.abort()}>Stop</button>
      ) : (
        <button onClick={handleSend} disabled={!prompt.trim()}>
          Send
        </button>
      )}

      <div
        className="answer"
        aria-live="polite"
        style={{ whiteSpace: 'pre-wrap' }}
      >
        {answer}
        {isStreaming && <span className="cursor">▍</span>}
      </div>

      {error && <p className="error">{error}</p>}
    </div>
  );
}

 

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:

TypeScript — src/main.ts
// src/main.ts
import compression from 'compression';

app.use(
  compression({
    filter: (req, res) =>
      res.getHeader('Content-Type') !== 'text/event-stream' &&
      compression.filter(req, res),
  }),
);

 

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:

Nginx Configuration
location /chat/stream {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 3600s;
    proxy_set_header Connection '';
}

 

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

Mistake

Why It Breaks Streaming

Fix

Listening to req.on('close')

In modern Node.js, req closes right after the POST body is parsed

Listen to res.on('close') and check !res.writableFinished

Sending raw text instead of JSON

Tokens containing \n split SSE frames prematurely

Wrap every chunk in JSON.stringify({ text })

Parsing network chunks directly

A chunk can hold half an SSE frame or multiple frames

Buffer until \r?\n\r?\n and flush on stream close

Enabling gzip/brotli on SSE

Compression middleware holds bytes back to build compression blocks

Exclude text/event-stream in compression filter

Leaving Nginx buffering enabled

Reverse proxy waits for upstream completion before sending bytes

Set X-Accel-Buffering: no and proxy_buffering off;

Assuming stream close = success

Dropped connections silently cut off answers mid-sentence

Require an explicit data: [DONE] marker before resolving

 

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

Work with Rorix

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.

How to Stream AI Like ChatGPT in NestJS & React: 5 Steps