Loading…
Loading documentation...
Stream a model's answer into a Next.js 16 page through your own API route, with the key kept on the server, a length limit and a Stop button.
Commands checked on 2026-10-27 with Next.js 16, Node.js 24, openai 7.32.
A page where a visitor types a question and reads the answer as the model writes it. The browser talks only to your own route; the route holds the provider's key on the server, refuses a question that is empty or too long, caps the length of the answer, and stops the model when the visitor presses Stop or closes the page.
app/, such as the example made in step 2 of Run a Next.js app as a systemd service on Ubuntu. The commands use its folder, ~/nextapp. If your app keeps its pages in src/app instead, put the two files below under src/ too./v1/chat/completions address. You need an API key, the API's base address and a model name, written here as YOUR_API_KEY, YOUR_BASE_URL (for OpenAI, https://api.openai.com/v1) and YOUR_MODEL.The official openai package talks to any API of that shape. The three settings go in .env.local, which Next.js reads on your machine and Git ignores.
cd ~/nextapp
npm install openai@7.32.0
printf 'AI_BASE_URL=%s\nAI_MODEL=%s\n' 'YOUR_BASE_URL' 'YOUR_MODEL' >> .env.local
printf 'AI_API_KEY=%s\n' 'YOUR_API_KEY' >> .env.local
None of the three names starts with NEXT_PUBLIC_, so none of them reaches the browser. On a server, put the same lines in the app's environment file, as in Keep secrets out of code, logs and images.
The route checks the question first, then asks for a streamed answer and passes the text on as it arrives. request.signal ends the model's work when the browser goes away, and cancel() does the same when the visitor stops reading.
mkdir -p app/api/answer
cat > app/api/answer/route.ts <<'EOF'
import OpenAI from "openai";
import type { NextRequest } from "next/server";
const MAX_QUESTION = 2000;
export async function POST(request: NextRequest) {
const body = await request.json().catch(() => null);
const question = typeof body?.question === "string" ? body.question.trim() : "";
if (!question || question.length > MAX_QUESTION) {
return Response.json({ error: `Ask a question of 1 to ${MAX_QUESTION} characters.` }, { status: 400 });
}
const client = new OpenAI({ apiKey: process.env.AI_API_KEY, baseURL: process.env.AI_BASE_URL });
let stream;
try {
stream = await client.chat.completions.create(
{
model: process.env.AI_MODEL ?? "",
messages: [
{ role: "system", content: "Answer in a few short sentences." },
{ role: "user", content: question },
],
max_tokens: 1000,
stream: true,
},
{ signal: request.signal },
);
} catch (error) {
console.error(JSON.stringify({ event: "model_request_failed", status: (error as { status?: number }).status ?? null }));
return Response.json({ error: "The model did not answer. Try again in a moment." }, { status: 502 });
}
const encoder = new TextEncoder();
const answer = new ReadableStream({
async start(controller) {
try {
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content;
if (text) controller.enqueue(encoder.encode(text));
}
} catch (error) {
if ((error as Error).name !== "AbortError") console.error(JSON.stringify({ event: "model_stream_failed" }));
} finally {
controller.close();
}
},
cancel() {
stream.controller.abort();
},
});
return new Response(answer, {
headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", "X-Accel-Buffering": "no" },
});
}
EOF
max_tokens caps the length, and so the cost, of every answer. X-Accel-Buffering: no tells an Nginx in front of the app to pass each part on at once.
The page reads the response body piece by piece and adds each piece to the answer. Stop aborts the request, which ends the model's work through the route.
mkdir -p app/ask
cat > app/ask/page.tsx <<'EOF'
"use client";
import { useRef, useState, type FormEvent } from "react";
export default function AskPage() {
const [question, setQuestion] = useState("");
const [answer, setAnswer] = useState("");
const [answering, setAnswering] = useState(false);
const request = useRef<AbortController | null>(null);
async function ask(event: FormEvent) {
event.preventDefault();
request.current = new AbortController();
setAnswer("");
setAnswering(true);
try {
const response = await fetch("/api/answer", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question }),
signal: request.current.signal,
});
if (!response.ok || !response.body) {
const body = await response.json().catch(() => ({}));
setAnswer(body.error ?? "Something went wrong. Try again.");
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
setAnswer((text) => text + decoder.decode(value, { stream: true }));
}
} catch (error) {
if ((error as Error).name !== "AbortError") setAnswer("The answer stopped. Try again.");
} finally {
setAnswering(false);
}
}
return (
<main style={{ maxWidth: 640, margin: "2rem auto", padding: "0 1rem" }}>
<form onSubmit={ask}>
<label htmlFor="question">Your question</label>
<textarea id="question" value={question} maxLength={2000} rows={3}
onChange={(event) => setQuestion(event.target.value)} style={{ display: "block", width: "100%" }} />
<button type="submit" disabled={answering || !question.trim()}>Ask</button>
<button type="button" onClick={() => request.current?.abort()} disabled={!answering}>Stop</button>
</form>
<p aria-live="polite" style={{ whiteSpace: "pre-wrap" }}>{answer}</p>
</main>
);
}
EOF
aria-live="polite" lets a screen reader announce the answer as it grows.
npm run dev
Open http://localhost:3000/ask, ask a question, and watch the answer appear a few words at a time. Leave it running for the checks.
If the app runs on a server, reach it from your computer through an SSH tunnel, ssh -L 3000:localhost:3000 you@your-server, and open the same address there. The development server sends its scripts only to localhost, so a page opened at the server's own address shows but never answers.
In a second terminal, ask the route with no question, then with a real one, and time each piece of the answer:
curl -s -w ' %{http_code}\n' -H 'Content-Type: application/json' -d '{"question":""}' http://localhost:3000/api/answer
node --input-type=module -e '
const t0 = Date.now(); let parts = 0, first = 0, text = "";
const res = await fetch("http://localhost:3000/api/answer", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question: "In one sentence, what is a hypervisor?" }) });
const reader = res.body.getReader(), decoder = new TextDecoder();
for (;;) { const { done, value } = await reader.read(); if (done) break; parts++; if (!first) first = Date.now() - t0; text += decoder.decode(value, { stream: true }); }
console.log(res.status, res.headers.get("content-type"), "parts", parts, "first after", first, "ms, all after", Date.now() - t0, "ms");
console.log(text);
'
The first line prints {"error":"Ask a question of 1 to 2000 characters."} 400. The second prints 200 text/plain; charset=utf-8, a number of parts above 1, the first part well before the last, and then the answer. A model that thinks before it answers, as reasoning models do, sends nothing for that time, so the first part can take some seconds.
"status":401. The provider refused the key. Check AI_API_KEY in .env.local, and restart npm run dev after any change to it: Next.js reads the file when it starts."status":404. The model name or the base address is wrong. Most providers list their models at YOUR_BASE_URL/models.X-Accel-Buffering: no header handles it; for another proxy, turn off response buffering for this route.max_tokens. Raise it, or ask for a shorter answer in the system message.request.current is set before fetch starts, as in step 3.Every Servers Are Up virtual machine and container includes an integrated HTML5 browser-based SSH, RDP, and VNC console in your dashboard, default-off inbound firewall rules with per-IP allow-lists, and full programmatic control via REST API v1 and Model Context Protocol (MCP). Explore our Virtual Datacenter Plans or reach out to Servers Are Up Support.