Models → Pricing → Docs → Blog → Changelog → Contact → Status →
Get started freeLog in

Streaming Chat in Next.js with the FreeModel API

Stream chat completions to a React UI in Next.js: an App Router route handler, a ReadableStream, a client-side reader, a Stop button and error handling.

A chat UI that shows the answer as it is written feels much faster than one that waits for the whole reply. This post wires FreeModel's streaming /v1/chat/completions into a Next.js App Router project: a route handler on the server, and a React component that renders the text as it arrives.

The architecture

  • Browser → POST /api/chat on your own Next.js server, with the conversation.
  • Route handler → FreeModel with stream: true, using your fm_ key from a server-only environment variable.
  • Route handler → browser: a plain-text stream of the answer.

The key never reaches the browser. That is the main reason for the route handler: anything in client code is public.

Step 1: set up the project

npx create-next-app@latest chat-demo --ts --app
cd chat-demo
npm install openai
echo "FREEMODEL_API_KEY=fm_your_key_here" > .env.local

Variables without the NEXT_PUBLIC_ prefix stay on the server, which is what we want here.

Step 2: the route handler

The OpenAI Node SDK parses FreeModel's server-sent events for us. We take the text deltas and write them into a ReadableStream that becomes the response body.

// app/api/chat/route.ts
import OpenAI from "openai";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const client = new OpenAI({
  apiKey: process.env.FREEMODEL_API_KEY,
  baseURL: "https://freemodel.in/v1",
});

type Msg = { role: "user" | "assistant"; content: string };

export async function POST(req: Request) {
  const { messages } = (await req.json()) as { messages: Msg[] };

  try {
    const stream = await client.chat.completions.create(
      {
        model: "gpt-6-luna",
        messages: [
          { role: "system", content: "You are a helpful assistant. Be concise." },
          ...messages.slice(-20), // keep the history bounded
        ],
        stream: true,
      },
      { signal: req.signal }, // browser disconnects -> stop upstream too
    );

    const encoder = new TextEncoder();
    const body = new ReadableStream<Uint8Array>({
      async start(controller) {
        try {
          for await (const chunk of stream) {
            const text = chunk.choices[0]?.delta?.content;
            if (text) controller.enqueue(encoder.encode(text));
          }
          controller.close();
        } catch (err) {
          controller.error(err); // mid-stream error frame or dropped connection
        }
      },
      cancel() {
        stream.controller.abort();
      },
    });

    return new Response(body, {
      headers: {
        "Content-Type": "text/plain; charset=utf-8",
        "Cache-Control": "no-cache, no-transform",
      },
    });
  } catch (err) {
    // errors before the first chunk: 401, 402, 403, 404, 429 ...
    const status = err instanceof OpenAI.APIError && err.status ? err.status : 500;
    const message = err instanceof OpenAI.APIError ? err.message : "Request failed";
    return Response.json({ error: message }, { status });
  }
}

Two details matter. Errors before streaming starts come back as normal HTTP errors, so the handler can forward the real status code. Errors during the stream arrive from FreeModel as an error frame before [DONE] (see the streaming docs); the SDK raises them inside the for await loop, and controller.error passes the failure on to the browser.

Step 3: the React component

The browser reads the response body chunk by chunk and appends each piece to the last message.

// app/page.tsx
"use client";
import { useRef, useState, type FormEvent } from "react";

type Msg = { role: "user" | "assistant"; content: string };

export default function ChatPage() {
  const [messages, setMessages] = useState<Msg[]>([]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const abortRef = useRef<AbortController | null>(null);

  const append = (piece: string) =>
    setMessages((prev) => {
      const next = [...prev];
      const last = next[next.length - 1];
      next[next.length - 1] = { ...last, content: last.content + piece };
      return next;
    });

  async function send(e: FormEvent) {
    e.preventDefault();
    const text = input.trim();
    if (!text || busy) return;

    const history: Msg[] = [...messages, { role: "user", content: text }];
    setMessages([...history, { role: "assistant", content: "" }]);
    setInput("");
    setBusy(true);
    const ac = new AbortController();
    abortRef.current = ac;

    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: history }),
        signal: ac.signal,
      });
      if (!res.ok || !res.body) {
        const data = await res.json().catch(() => ({}));
        append(`[Error ${res.status}: ${data.error ?? "request failed"}]`);
        return;
      }
      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        append(decoder.decode(value, { stream: true }));
      }
    } catch (err) {
      if ((err as Error).name !== "AbortError") append("\n[Connection lost]");
    } finally {
      setBusy(false);
      abortRef.current = null;
    }
  }

  return (
    <main style={{ maxWidth: 720, margin: "40px auto", fontFamily: "system-ui" }}>
      {messages.map((m, i) => (
        <p key={i} style={{ whiteSpace: "pre-wrap" }}>
          <strong>{m.role === "user" ? "You" : "AI"}:</strong> {m.content}
        </p>
      ))}
      <form onSubmit={send} style={{ display: "flex", gap: 8 }}>
        <input value={input} onChange={(e) => setInput(e.target.value)}
               placeholder="Ask something" style={{ flex: 1 }} />
        {busy
          ? <button type="button" onClick={() => abortRef.current?.abort()}>Stop</button>
          : <button type="submit">Send</button>}
      </form>
    </main>
  );
}

Run npm run dev, open http://localhost:3000, and the answer appears word by word. decoder.decode(value, { stream: true }) matters: a multi-byte character (an emoji, Hindi or Bengali text) can be split across two chunks, and the streaming decoder stitches it back together.

Plain text or SSE to the browser?

OptionGood forCost
Plain text (this post)Chat UIs that only show the answerSimplest client; no metadata
Re-emit SSE / JSON linesShowing tool calls, reasoning or usage in the UIYou parse events on the client
A UI library's stream formatProjects already using that libraryTies you to its protocol

If you need more than text, send one JSON object per line ({"type":"text","value":"..."}) and split on newlines in the browser. The SSE guide covers the raw event format, including tool-call deltas and the usage chunk.

Errors users will actually see

  • 429 — the per-minute limit is full. The handler forwards the status; retry after the Retry-After seconds or show "busy". The SDK already retries 429 twice on its own.
  • 402 — the plan's tokens are used up. Show a clear message; retrying will not help.
  • 403 upgrade_required — a free key asked for a paid model, for example Claude Sonnet.

The full list is in handling 402, 403 and 429 errors.

Deployment notes

  • Keep runtime = "nodejs" unless you have tested the SDK on your edge runtime.
  • FreeModel keeps a /v1/chat/completions stream open for up to 15 minutes (up to an hour on /v1/messages) and sends a keep-alive comment every 8 seconds. Your hosting platform may cut functions off sooner — check its timeout for streaming responses.
  • Proxies that buffer responses break streaming. Cache-Control: no-transform helps; on nginx, also disable proxy buffering for this route.
  • Streamed requests are counted after the stream completes. If the user presses Stop, the output already generated still counts.

FAQ

Can I call FreeModel directly from the browser?

You should not. Anything in browser code is public, so your fm_ key would leak. Call the API from a route handler and keep the key in a server-only environment variable.

Why send plain text to the browser instead of SSE?

The browser only needs the text. Parsing SSE once on the server keeps the client to a simple stream reader. Forward SSE if you also need tool calls or usage in the browser.

Does the Stop button stop the charge?

It stops generation. The output you already received still counts, together with the input tokens.

Can I use a Claude model in this app?

Yes, change the model id, for example to claude-sonnet-5. Claude models other than Claude Haiku 5.5 need a paid plan; a free key gets 403 upgrade_required.

Ready to build?

Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.