🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

AI Integration: Streaming Chat in Next.js

Next.js AdvancedđŸŸĸ Free Lesson

AI Integration: Streaming Chat in Next.js

Most AI demos work exactly once and then fall apart in production for reasons that have nothing to do with model quality: the provider key ends up in the browser bundle, the answer sits blank for four seconds before the first character appears, one curious user burns fifty dollars of tokens in an afternoon, or the transcript re-renders on every single token. This lesson builds the endpoint and the client that consumes it, then walks through the decisions that separate a prototype from a feature you can put behind a paywall.

Prerequisites

  • !Route handlers and the app directory
  • !Async functions, Promises, and fetch
  • !Environment variables in Next.js

What You'll Learn

  • 1Explain what a route handler must own when proxying a model provider
  • 2Stream generated tokens from the server to the browser incrementally
  • 3Choose between the Node and Edge runtimes with a concrete checklist
  • 4Bound token spend with history limits, output caps, and rate limits

What the server has to own

When a Next.js app talks to a model provider, the route handler in the middle is not ceremony — it is the security boundary. Three responsibilities live there and nowhere else. First, authentication: you decide which signed-in user is allowed to spend money, and you reject anonymous calls before a single token is generated. Second, validation: the browser sends a JSON array of messages, and an untrusted array can be megabytes long, smuggle a system-prompt override, or claim roles the model should never accept. Third, budget: you clamp the conversation window, set a maximum output length, and record what was consumed.

There is a second reason not to call the provider from a Server Component. A Server Component renders once and produces HTML plus a serialized payload; it has no natural way to hand a half-finished answer to the browser as it arrives. Streaming needs a Response whose body can be written to repeatedly, and a route handler is exactly that. Keep the model call in a route handler, keep the key in an environment variable on the server, and let the component tree only read the stream.

A route handler that streams every token

Byte-level streaming sounds complicated, but the mechanics are small: create a ReadableStream, forward each delta the provider emits as an enqueue, and close when the provider stops. The headers matter as much as the body. A no-store cache directive stops intermediaries from caching a personal answer, and the anti-buffering header tells nginx-style proxies not to hold the response until it completes — the classic cause of an answer that arrives all at once after a long pause.

// app/api/chat/route.js
import { OpenAI } from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const MAX_OUTPUT_TOKENS = 600;
const HISTORY_LIMIT = 12;

export async function POST(request) {
  const { messages } = await request.json();

  if (!Array.isArray(messages) || messages.length === 0) {
    return Response.json({ error: 'messages required' }, { status: 400 });
  }

  const trimmed = messages
    .filter((m) => m.role === 'user' || m.role === 'assistant')
    .slice(-HISTORY_LIMIT);

  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      try {
        const completion = await openai.chat.completions.create(
          {
            model: 'gpt-4o-mini',
            messages: trimmed,
            max_tokens: MAX_OUTPUT_TOKENS,
            stream: true,
          },
          { signal: request.signal }
        );

        for await (const event of completion) {
          const delta = event.choices[0].delta.content;
          if (delta) controller.enqueue(encoder.encode(delta));
        }
      } catch (err) {
        if (err.name !== 'AbortError') controller.error(err);
      } finally {
        controller.close();
      }
    },
  });

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      'Cache-Control': 'no-store, no-transform',
      'X-Accel-Buffering': 'no',
    },
  });
}

Two details in that handler deserve emphasis. Slicing the history bounds what the model sees, so a long chat cannot silently grow the request and the bill. Passing the request signal into the SDK call means that when the user navigates away or hits stop, upstream generation is actually cancelled instead of continuing to bill you for a response nobody will read.

Reading the stream in the browser

The fetch Response exposes its body as a stream, and a reader hands you chunks as they land. The pattern that matters is the one thin implementations usually get wrong: append the new text to the assistant message rather than rebuilding the transcript, and keep an AbortController so the stop button really stops.

'use client';
import { useState, useRef } from 'react';

export default function Chat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [pending, setPending] = useState(false);
  const abortRef = useRef(null);

  async function send(event) {
    event.preventDefault();
    const content = input.trim();
    if (!content || pending) return;

    const history = [...messages, { role: 'user', content }];
    setMessages([...history, { role: 'assistant', content: '' }]);
    setInput('');
    setPending(true);

    abortRef.current = new AbortController();
    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ messages: history.slice(-12) }),
      signal: abortRef.current.signal,
    });

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

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      const chunk = decoder.decode(value, { stream: true });
      setMessages((current) => {
        const copy = [...current];
        const last = copy[copy.length - 1];
        copy[copy.length - 1] = { ...last, content: last.content + chunk };
        return copy;
      });
    }

    setPending(false);
  }

  function stop() {
    if (abortRef.current) abortRef.current.abort();
    setPending(false);
  }

  return (
    <form onSubmit={send}>
      {messages.map((m, i) => (
        <p key={i} className={m.role}>{m.content}</p>
      ))}
      <input value={input} onChange={(e) => setInput(e.target.value)} />
      <button type="button" onClick={stop} disabled={!pending}>Stop</button>
      <button type="submit" disabled={pending}>Send</button>
    </form>
  );
}

Read the loop closely. Decoding with the streaming flag keeps multi-byte characters that split across chunk boundaries from coming out as garbage, and the functional state update guarantees you always append to the newest array even when React batches two chunks together. Rendering the whole array on every chunk is fine up to a few hundred messages; beyond that, memoize individual message rows, because token-rate updates are the fastest way to make a chat interface feel janky.

Node or Edge: choose deliberately

The rule of thumb is simple: if the call is a single HTTP request to a provider and you want the first token to arrive fast from anywhere in the world, the Edge runtime is attractive. If you need background tool execution, a database driver that leans on Node APIs, or a generation that may run for a minute, stay on Node. Streaming works on both runtimes; package compatibility is what actually decides the choice.

ConcernNode.js runtimeEdge runtime
Cold startOften hundreds of millisecondsFrequently under 50 ms
SDK compatibilityFull, including file and polling APIsHTTP-only SDKs; some packages fail
Long generationsComfortable for minute-long runsRisk of per-invocation limits
Local database driversSupportedUsually unsupported
Best fitTool loops, RAG, heavy providersShort completions, geo-routed endpoints

Check that your SDK does not pull in native or filesystem-dependent modules before you set the runtime to edge, because that failure surfaces at request time rather than at build time — exactly when a real user is waiting.

Keeping spend bounded

A leaked key is the loud failure. The quiet one is a feature that is simply too easy to call. Put a rate limit in front of the endpoint, and make the limit about cost rather than request count: a request that generates six hundred output tokens is not the same as one that generates six.

javascript
// lib/rate-limit.js — fixed window per user, backed by Redis
import { redis } from './redis';

const WINDOW_SECONDS = 60;
const MAX_TOKENS_PER_WINDOW = 4000;

export async function consumeTokenBudget(userId, estimatedTokens) {
  const windowIndex = Math.floor(Date.now() / (WINDOW_SECONDS * 1000));
  const key = 'ai:' + userId + ':' + windowIndex;
  const used = await redis.incrBy(key, estimatedTokens);
  if (used === estimatedTokens) await redis.expire(key, WINDOW_SECONDS);

  if (used > MAX_TOKENS_PER_WINDOW) {
    return { allowed: false, remaining: 0 };
  }
  return { allowed: true, remaining: MAX_TOKENS_PER_WINDOW - used };
}

Estimate before you generate: prior turns plus the new user message gives a token count you can charge against the budget up front, then reconcile with the provider's reported usage when the stream finishes. Persisting actual usage per user per day turns cost surprises into a graph you can look at weekly, and makes it possible to alert when one account's curve goes vertical.

Latency: what the user actually feels

Time to first token is the metric users feel; total completion time is the metric dashboards report. A model that answers in four seconds but shows nothing for three of them feels slower than one that starts printing immediately and finishes a beat later. Three levers move first token: prompt size, because you should send only the history that matters; provider region, because a nearby endpoint saves a round trip; and any work you do before the stream opens, because retrieval, guardrail calls, and database reads all sit on the critical path. Run them in parallel before the stream if they cannot be deferred, or move them after the first token if they can. On the render side, write each delta straight to the transcript instead of re-parsing markdown for the entire conversation on every chunk, and give the streaming paragraph a stable key so React does not tear it down and rebuild it six hundred times.

Failures you should handle on day one

Streams break in ways plain requests do not. The connection can drop halfway through a sentence, the provider can rate-limit you after you have already started writing to the client, and the user can navigate away mid-generation. Because you have already committed a successful response, you cannot swap in a friendly error page — the convention is to end the stream and let the client mark the message as interrupted, offering a retry that reuses the same message array. Set timeouts on the provider call rather than on the Response, so a slow model fails before your platform kills the invocation. Log every failure with a request id, the model name, the prompt token count, and whether the stream had already begun; debugging an empty chat box with no identifiers is miserable.

Common Mistakes

Storing the provider key in an environment variable prefixed with NEXT_PUBLIC_

Fix: Only server-side variables stay secret; anything with that prefix is inlined into the client bundle and readable by anyone.

Awaiting the whole completion and then returning it as one string

Fix: Stream deltas as they arrive; a buffered response makes a four-second answer look like a ten-second hang.

Forwarding the entire chat history on every turn with no cap

Fix: Slice to a fixed window and summarize older turns; request cost grows linearly with turns otherwise.

Ignoring the request signal when the user leaves the page

Fix: Pass the signal into the SDK call so generation actually stops and stops billing.

Returning an empty bubble when generation fails mid-stream

Fix: Mark the message as interrupted in the client and offer a retry with the same messages array.

Best Practices

  • Validate the messages array with a schema before it reaches the provider
  • Clamp history length and set an explicit max output token count on every request
  • Log model, prompt tokens, completion tokens, latency, and user id for each generation
  • Test the endpoint with throttled network to observe true time to first token
  • Keep provider calls in route handlers; Server Components should never own streaming

Interview Questions

Q1: Why stream from a route handler instead of a Server Component?

A Server Component renders once and has no way to push a partial body to the browser. A route handler returns a Response whose body can be written to repeatedly, which is exactly what incremental token delivery needs.

Q2: How do you stop an in-flight generation when the user presses Stop?

Keep an AbortController in the client, abort the fetch, and pass the request signal into the provider SDK call so the upstream request is cancelled too, not just the local read loop.

Q3: Where must the API key live, and what goes wrong with the public prefix?

Server-side only. The NEXT_PUBLIC_ prefix inlines the value into the browser bundle, exposing it to every visitor.

Q4: How would you cap spend per user?

Bound history and output tokens per request, estimate tokens before calling, then enforce a per-user rolling token budget in Redis and log actual usage for reconciliation.

Key Takeaways

  • The route handler is the security boundary: authenticate, validate, and budget before any token is generated.
  • Stream with a ReadableStream and anti-buffering headers, then append deltas in the client instead of rebuilding the transcript.
  • Node versus Edge is decided by SDK compatibility and generation length, not by marketing claims about latency.
  • Cost control is three layers: history caps, output caps, and a per-user token budget that reconciles with reported usage.
  • Time to first token is the user-facing metric; anything you do before the stream opens sits on the critical path.
  • Plan for interrupted streams on day one, including a retry path and identifiers in every log line.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement