Building Real-Time AI Streaming UI with Nuxt 4 and SSE

Hello, this is Lovefield.

When integrating LLM features into a web application, perceived latency is one of the first UX hurdles you encounter. Waiting for a model to finish generating an entire response before returning a single JSON payload leaves users staring at a spinner for 5 to 20 seconds—often long enough for them to abandon the page.

Server-Sent Events (SSE) solves this by dramatically reducing Time To First Token (TTFT). Without standing up a separate WebSocket infrastructure, your server can push generated text tokens to the browser in real time over standard HTTP.

In this post, we will build a clean, production-ready AI streaming UI using Nuxt 4's Nitro server, the Web Streams API, and a Vue 3.5 composable.

Why Choose SSE Over WebSockets for AI Streaming

While WebSockets are great for bidirectional real-time apps, AI text generation is fundamentally asymmetric: the client sends a single POST prompt, and the server streams tokens back in one direction.

  • Simpler Infrastructure: SSE runs over standard HTTP/1.1 and HTTP/2, working smoothly with existing Nginx reverse proxies and load balancers.

  • Proxy-Friendly: Allowing text/event-stream is straightforward even in strict corporate network environments.

  • Clean Lifecycle Management: Combining fetch with ReadableStream ties each stream directly to a single request lifecycle without manual heartbeat or reconnection boilerplate.

Implementing an SSE Endpoint in Nuxt 4 Nitro

The browser's built-in EventSource API only supports GET requests and lacks custom headers or large JSON request bodies. In production, the standard approach is to accept prompts via POST and respond with a text/event-stream ReadableStream.

Here is a clean implementation in server/api/chat.post.ts:

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

// server/api/chat.post.ts
export default defineEventHandler(async (event) => {
  const { prompt } = await readBody<{ prompt: string }>(event);

  if (!prompt?.trim()) {
    throw createError({ statusCode: 400, statusMessage: 'Prompt is required.' });
  }

  // Configure SSE response headers
  setResponseHeaders(event, {
    'Content-Type': 'text/event-stream; charset=utf-8',
    'Cache-Control': 'no-cache, no-transform',
    'Connection': 'keep-alive',
    'X-Accel-Buffering': 'no', // Disable Nginx proxy buffering
  });

  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      try {
        // In production, iterate over your LLM SDK's async stream here
        const mockTokens = ['With ', 'Nuxt 4 ', 'and SSE, ', 'you can ', 'build smooth ', 'real-time ', 'AI streaming UIs.'];

        for (const token of mockTokens) {
          // Stop generating if the client disconnects
          if (event.node.req.destroyed) break;

          const payload = JSON.stringify({ text: token });
          controller.enqueue(encoder.encode(`data: ${payload}\n\n`));
          await new Promise((resolve) => setTimeout(resolve, 120));
        }

        controller.enqueue(encoder.encode('data: [DONE]\n\n'));
      } catch (error) {
        const errPayload = JSON.stringify({ error: 'Failed to generate stream.' });
        controller.enqueue(encoder.encode(`data: ${errPayload}\n\n`));
      } finally {
        controller.close();
      }
    },
  });

  return sendStream(event, stream);
});

Pay close attention to X-Accel-Buffering: no. When Nginx sits in front of your Nuxt server as a reverse proxy, omitting this header causes Nginx to buffer chunks until the response finishes, completely defeating real-time streaming.

Parsing Chunks and Handling Cancellation in Vue 3.5

On the client side, combine response.body.getReader() with TextDecoder. Because network packets can split a single data: {...}\n\n message across two chunks, always buffer incomplete lines until a double newline (\n\n) arrives.

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

// app/composables/useAiStream.ts
import { ref, onUnmounted } from 'vue';

export function useAiStream() {
  const answer = ref('');
  const isStreaming = ref(false);
  const errorMessage = ref<string | null>(null);

  let abortController: AbortController | null = null;

  const stop = () => {
    abortController?.abort();
    abortController = null;
    isStreaming.value = false;
  };

  const ask = async (prompt: string) => {
    stop(); // Safely cancel any active stream
    answer.value = '';
    errorMessage.value = null;
    isStreaming.value = true;

    abortController = new AbortController();

    try {
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt }),
        signal: abortController.signal,
      });

      if (!response.ok || !response.body) {
        throw new Error(`Server error: ${response.status}`);
      }

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

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

        // Pass { stream: true } so multibyte UTF-8 characters never break across chunks
        buffer += decoder.decode(value, { stream: true });
        const events = buffer.split('\n\n');
        buffer = events.pop() ?? '';

        for (const rawEvent of events) {
          const line = rawEvent.trim();
          if (!line.startsWith('data: ')) continue;

          const data = line.slice(6);
          if (data === '[DONE]') return;

          const parsed = JSON.parse(data) as { text?: string; error?: string };
          if (parsed.error) throw new Error(parsed.error);
          if (parsed.text) answer.value += parsed.text;
        }
      }
    } catch (error) {
      if (error instanceof DOMException && error.name === 'AbortError') {
        return; // Intentional user cancellation
      }
      errorMessage.value = error instanceof Error ? error.message : 'An unexpected error occurred.';
    } finally {
      isStreaming.value = false;
      abortController = null;
    }
  };

  // Clean up any open stream when the component unmounts
  onUnmounted(stop);

  return { answer, isStreaming, errorMessage, ask, stop };
}

Passing { stream: true } to decoder.decode() is essential for internationalized apps. Multibyte UTF-8 characters (such as Korean, Japanese, or emojis) can be split across chunk boundaries; without stream: true, they render as broken replacement characters (``).

Preventing Rendering Bottlenecks During Fast Streaming

When an LLM emits dozens of tokens per second, re-running a heavy Markdown parser and syntax highlighter on the entire message for every single token can stutter the main thread.

  • Frame-Based Batching: Accumulate incoming tokens in a plain string variable and flush them to your reactive ref on requestAnimationFrame to cap UI updates cleanly at 60fps.

  • Block-Level Memoization: Split completed paragraphs (separated by \n\n) into static rendered blocks and only re-parse the actively streaming final block.

  • Immediate Stop Controls: Swap the submit button for a "Stop Generating" button wired to stop() while isStreaming is true, giving users instant control over long responses.

Summary

You do not need heavy third-party wrappers to deliver a responsive AI chat experience. Combining Nuxt 4 Nitro streams, native ReadableStream, and AbortController keeps your bundle lightweight and your architecture transparent.

With X-Accel-Buffering: no for reverse proxies, { stream: true } for safe UTF-8 decoding, and automatic cleanup on unmount, your streaming UI will stay fast and reliable in production.

This article was generated by AI.

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.

Configuring Gemini Agents in Antigravity with AGENTS.md and Skills

A practical guide to setting up the .agents directory, AGENTS.md, and progressive-disclosure skills in Google Antigravity so Gemini agents consistently follow your team's code style and API design standards.

ETC

Building a Multi-Agent Orchestra with Antigravity IDE and Discord MCP

Server

v5.0