Mistral LLM Streaming Chat App: Build It in Node
A mistral llm streaming chat app needs three pieces: a small server that holds your key and streams tokens, a browser page that renders them as they arrive, and a rule for trimming history so the conversation never outgrows the context window. This tutorial builds all three against our API in under 100 lines.
Last updated

Keep the API key on the server; the browser talks to your own /chat route over SSE.
Read usage at the end of the stream to compute exact cost per reply.
Trim old messages to a token cap so each request stays cheap and inside 100,000 tokens.
Each open stream holds a concurrency slot, 8 on a full key, until it finishes.
Summary
How the pieces fit
The browser sends the conversation to your server. The server calls https://api.mistralllmapi.com/v1 with stream: true and forwards each text delta to the browser as a server-sent event. When the model finishes, the server sends one last event with the cost. Your API key never leaves the server.
You need Node 18 or newer. Create a folder, run npm init -y, set "type": "module" in package.json, and install the two dependencies with npm install express openai. Put the page in a public folder as index.html.
The streaming server
The route trims history, opens the stream and relays deltas. It also reads the response headers, where X-Balance-USD reports your remaining credit.
import express from "express";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.mistralllmapi.com/v1",
apiKey: process.env.API_KEY,
});
const app = express();
app.use(express.json({ limit: "1mb" }));
app.use(express.static("public"));
const SYSTEM = { role: "system", content: "You are a friendly, concise assistant." };
const MAX_PROMPT_TOKENS = 20000;
const IN_RATE = 0.15 / 1e6;
const OUT_RATE = 0.5 / 1e6;
const approx = (m) => Math.ceil(m.content.length / 4) + 4;
function trim(history) {
const kept = [];
let total = approx(SYSTEM);
for (let i = history.length - 1; i >= 0; i--) {
const t = approx(history[i]);
if (total + t > MAX_PROMPT_TOKENS) break;
kept.unshift(history[i]);
total += t;
}
return [SYSTEM, ...kept];
}
app.post("/chat", async (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
const send = (obj) => res.write(`data: ${JSON.stringify(obj)}\n\n`);
try {
const { data: stream, response } = await client.chat.completions
.create({ model: "uncensored", messages: trim(req.body.messages), stream: true })
.withResponse();
res.on("close", () => stream.controller.abort());
let usage = null;
for await (const chunk of stream) {
const delta = chunk.choices?.[0]?.delta?.content;
if (delta) send({ delta });
if (chunk.usage) usage = chunk.usage;
}
const cost = usage
? usage.prompt_tokens * IN_RATE + usage.completion_tokens * OUT_RATE
: null;
send({ done: true, usage, cost, balance: response.headers.get("x-balance-usd") });
} catch (err) {
send({ error: err.status === 429 ? "busy, try again in a few seconds" : "request failed" });
}
res.end();
});
app.listen(3000, () => console.log("http://localhost:3000"));Start it with API_KEY=your-key node server.js. The res.on("close") line matters: if the user closes the tab, it aborts the upstream stream so the concurrency slot is released rather than held until the answer completes.
The browser side
The page needs a message area, a text input with a form, and a small status line. The script below posts the history and reads the event stream with fetch, which works with a POST body, unlike the built-in EventSource.
const history = [];
const out = document.querySelector("#out");
const status = document.querySelector("#status");
async function send(text) {
history.push({ role: "user", content: text });
const bubble = document.createElement("div");
out.append(bubble);
const res = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: history }),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let reply = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const events = buffer.split("\n\n");
buffer = events.pop();
for (const ev of events) {
if (ev.startsWith("data: ") === false) continue;
const msg = JSON.parse(ev.slice(6));
if (msg.delta) { reply += msg.delta; bubble.textContent = reply; }
if (msg.error) bubble.textContent = msg.error;
if (msg.done && typeof msg.cost === "number") {
status.textContent = `This reply cost $${msg.cost.toFixed(5)}, balance $${msg.balance}`;
}
}
}
history.push({ role: "assistant", content: reply });
}Set textContent, not innerHTML, when you render model output. Model text is untrusted input, and treating it as HTML opens the door to script injection.
Trimming history for the context window
The window is 100,000 tokens for prompt and completion together, so a chat that runs long enough would eventually fail. The trim function walks backward from the newest message and keeps messages until it reaches a budget, here 20,000 tokens, always keeping the system prompt. The estimate is the character count divided by four, which is rough but safe when your cap sits far below the limit.
Pick the cap with cost in mind. Input is billed on every turn, so a 20,000-token prompt costs at most 20,000 × $0.15 ÷ 1,000,000 = $0.003 per request. A cap of 60,000 would allow $0.009 per request. If the story or the rules of a role must never be forgotten, pin them in the system prompt, or keep a running summary there and drop the turns it already covers.
You can refine the estimate. After each reply, usage.prompt_tokens tells you the real size of what you sent, so you can calibrate the characters-per-token ratio and trim earlier or later.
Tracking cost per reply
The final stream chunk carries usage, and the server turns it into dollars with the published rates. A reply with 12,000 prompt tokens and 600 completion tokens costs 12,000 × $0.15 ÷ 1,000,000 = $0.0018 plus 600 × $0.50 ÷ 1,000,000 = $0.0003, so $0.0021. Sum the values per user or per session to see which chats cost the most.
If a stream ends without a usage object, the code returns null instead of guessing, and the X-Balance-USD value on the next response gives you ground truth by difference. Failed or refused requests are not charged, so errors do not appear in your totals.
Harden it before you share it
The demo trusts the client too much. The browser sends the whole message list, so a user could include a message with the system role and rewrite your instructions. On the server, keep only user and assistant roles, require string content, and cap the number and length of messages.
Add a per-IP or per-account limit on the /chat route, since each call spends your credit and takes a concurrency slot. A user who loops requests can use up all 8 slots and starve everyone else. A small queue with a maximum length, returning a busy message when it is full, protects both your budget and your other users.
Finally, log the X-Request-Id value of failed calls. It is the quickest way to trace one bad reply when you contact support.
Test it and add a stop button
Before you open the page, test the route alone. The -N flag turns off curl's output buffering, so you see events as they arrive.
curl -N http://localhost:3000/chat \
-H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"Write two sentences about the sea."}]}'If the text appears all at once at the end, something between you and the server is buffering. Behind nginx, add the response header X-Accel-Buffering: no in the route and check that compression is not applied to event streams.
A stop button needs an AbortController. Pass its signal to fetch and call abort() on click. The server's res.on("close") handler then cancels the upstream stream, which frees the concurrency slot and stops further output tokens from being generated.
Also test the failure paths on purpose. Stop the server mid-reply and confirm the page shows an error instead of freezing. Send a request with a wrong key and check that the message reaches the user without exposing details. Open two tabs and send replies at the same time to see two streams share the key's slots.
const controller = new AbortController();
fetch("/chat", { method: "POST", signal: controller.signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: history }) });
document.querySelector("#stop").onclick = () => controller.abort();Limits, errors and next steps
A full key allows 8 concurrent requests and 300 per minute, a trial key 2 and 60. Every open reply holds a slot until its stream ends, so a chat app with many simultaneous users needs a queue or a friendly busy message. The server above maps a 429 to "busy, try again in a few seconds"; on overload the API sends Retry-After: 5, so a client retry after that long is reasonable.
From here, add a stop button that aborts the fetch, persist conversations in a database, and add tool calling if your app needs it. Details for every parameter are in the API docs, and the common mistakes page lists traps worth knowing before launch. Get a key and the free trial on the API key page; rates are on the pricing page.
More guides
FAQ
Why stream instead of waiting for the full answer?
Users see text almost at once, and long answers do not sit behind a silent connection that proxies might cut off.
Can I call the API directly from the browser?
You should not. That would expose your key to every visitor. Call it from your server and stream the result to the browser.
How do I stop the history from exceeding the context window?
Trim the oldest messages to a token budget before each request and keep the system prompt. The window is 100,000 tokens for prompt and completion.
How do I know what each reply cost?
Read the usage at the end of the stream and apply $0.15 per 1M input tokens and $0.50 per 1M output tokens. The X-Balance-USD header shows your remaining credit.
Get your API key
Sign up, copy the key, update your base URL. That is all.