Connecting a web frontend to DeepSeek-R1 via deepseek-reasoner feels wonderfully straightforward right up to the moment your chat UI looks completely dead.
You hit submit. You wait five seconds, ten seconds, twenty-five seconds. The user sees a frozen loading spinner and assumes the request timed out. Then, suddenly, a tidy three-sentence final answer appears out of nowhere. The entire Chain-of-Thought—the explicit reason you picked DeepSeek’s reasoning model over a cheaper commodity LLM—vanished into thin air.
At 365Finds, we have watched developer after developer fall into this exact trap. The root cause is deceptive simplicity: the DeepSeek API adheres strictly to the OpenAI Chat Completions protocol, but it does not pipe the reasoning chain through the classic delta.content channel. Instead, it introduces a separate, parallel stream field: delta.reasoning_content.
If your client-side parser only listens for delta.content, your application is functionally blind during the entire thinking phase. Here is how the wire protocol actually behaves, why naive React implementations crash browser framerates, and the exact dual-buffer architecture 365Finds recommends for production web applications.
1. The Wire Protocol: How DeepSeek Splits the Stream
When you invoke deepseek-reasoner with "stream": true, the SSE (Server-Sent Events) connection does not emit reasoning steps as <think> text tags embedded in content. DeepSeek separates internal reasoning from the final conversational answer right at the payload level.
Each streamed chunk delivers a JSON payload matching this lifecycle:
// Phase 1: Reasoning Stream
data: {"choices":[{"delta":{"role":"assistant","reasoning_content":"Let's"},"finish_reason":null}]}
data: {"choices":[{"delta":{"reasoning_content":" verify the constraint"},"finish_reason":null}]}
data: {"choices":[{"delta":{"reasoning_content":" first."},"finish_reason":null}]}
// Phase 2: Transition (reasoning_content ceases, content begins)
data: {"choices":[{"delta":{"content":"To"},"finish_reason":null}]}
data: {"choices":[{"delta":{"content":" solve this problem..."},"finish_reason":null}]}
// Phase 3: Completion
data: {"choices":[{"delta":{},"finish_reason":"stop"}]}
data: [DONE]
Notice the critical structural rules:
- Mutually Exclusive Deltas: During Phase 1,
delta.reasoning_contentcarries partial token strings whiledelta.contentis omitted or empty. During Phase 2,delta.reasoning_contentstops arriving, anddelta.contentdelivers the visible answer. - Finish Reason Nullity:
finish_reasonremainsnullthroughout both phases until the final termination chunk fires"stop". If your parser checksfinish_reasonto detect the end of thinking, it will fail. - Reasoning Token Volume: A complex math or coding prompt can easily generate 4,000 to 12,000 reasoning tokens before a single character of
contentarrives.
2. The Dual-Buffer Streaming Architecture
Because reasoning tokens arrive first and rapidly, a web application needs two distinct accumulation buffers and a clean state machine.
[ DeepSeek API / SSE Stream ]
|
+-----------v-----------+
| SSE Chunk Parser |
+-----------+-----------+
|
+-----------+-----------+
| |
[ reasoning_content ] [ content ]
| |
v v
+-----------------+ +-----------------+
| Reasoning Buffer| | Answer Buffer |
| (Collapsible UI)| | (Main Message) |
+-----------------+ +-----------------+
The Client-Side Stream Parser
Here is a robust, framework-agnostic reader that consumes the ReadableStream from fetch, handles fragmented TCP packets, and dispatches deltas into separate callbacks:
interface StreamCallbacks {
onReasoningDelta: (delta: string) => void;
onContentDelta: (delta: string) => void;
onDone: () => void;
onError: (err: Error) => void;
}
export async function consumeDeepSeekStream(
response: Response,
callbacks: StreamCallbacks
) {
if (!response.body) {
callbacks.onError(new Error("Response body is null"));
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
// Retain incomplete trailing line
buffer = lines.pop() ?? "";
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith(":")) continue; // Skip comments and heartbeats
if (trimmed === "data: [DONE]") {
callbacks.onDone();
return;
}
if (trimmed.startsWith("data: ")) {
const jsonStr = trimmed.slice(6);
try {
const parsed = JSON.parse(jsonStr);
const delta = parsed.choices?.[0]?.delta;
if (!delta) continue;
if (delta.reasoning_content) {
callbacks.onReasoningDelta(delta.reasoning_content);
}
if (delta.content) {
callbacks.onContentDelta(delta.content);
}
} catch (e) {
// Buffer boundary cut a JSON string; keep it in buffer
console.warn("Malformed chunk ignored:", jsonStr);
}
}
}
}
callbacks.onDone();
} catch (err) {
callbacks.onError(err as Error);
} finally {
reader.releaseLock();
}
}
3. UI Rendering: The Performance Bottleneck Most Teams Miss
Here is where 365Finds takes a strong stand: Do not feed raw reasoning token deltas directly into a reactive Markdown parser.
When a reasoning model hits a stride, DeepSeek can emit 40 to 70 tokens per second. If each token fires a React state update (setReasoning(prev => prev + delta)), you trigger 50 DOM recalculations per second. Combine that with a heavy Markdown library like react-markdown with syntax highlighting (rehype-highlight), and you will freeze the main thread. Mobile browsers will stutter, input boxes will lag, and fans will spin up.
The 365Finds Rendering Strategy
- Decouple Stream Ingestion from Paint: Accumulate incoming deltas in a mutable ref (
useRef). Flush those chunks into state on an animation frame loop (requestAnimationFrame) or a throttled 60ms ticker. - Lightweight Reasoning Render: During the active thinking phase, render the reasoning buffer as raw monospace text using CSS
white-space: pre-wrap; font-family: monospace;. Users do not need rendered tables or formatted LaTeX while the model is still changing its mind. Only run full Markdown parsing on the reasoning text onceonDonetriggers. - Collapsible "Thinking" Container: Place the reasoning block inside a
<details>disclosure widget or an animated accordion. Keep it open whilereasoning_contentis actively arriving; automatically collapse it (or collapse it with an option to expand) when the firstcontentdelta lands.
Here is a streamlined React implementation:
import React, { useState, useRef, useEffect } from "react";
export function DeepSeekMessageView({ streamResponse }: { streamResponse: Response }) {
const [reasoning, setReasoning] = useState("");
const [content, setContent] = useState("");
const [isThinking, setIsThinking] = useState(true);
const reasoningRef = useRef("");
const contentRef = useRef("");
const rafId = useRef<number | null>(null);
useEffect(() => {
// Throttled UI paint loop
const updateUI = () => {
setReasoning(reasoningRef.current);
setContent(contentRef.current);
rafId.current = requestAnimationFrame(updateUI);
};
rafId.current = requestAnimationFrame(updateUI);
consumeDeepSeekStream(streamResponse, {
onReasoningDelta: (chunk) => {
reasoningRef.current += chunk;
},
onContentDelta: (chunk) => {
if (isThinking) setIsThinking(false);
contentRef.current += chunk;
},
onDone: () => {
if (rafId.current) cancelAnimationFrame(rafId.current);
setReasoning(reasoningRef.current);
setContent(contentRef.current);
setIsThinking(false);
},
onError: (err) => console.error("Stream error:", err),
});
return () => {
if (rafId.current) cancelAnimationFrame(rafId.current);
};
}, [streamResponse]);
return (
<div className="message-container space-y-4">
{reasoning && (
<details open={isThinking} className="rounded border border-neutral-700 bg-neutral-900 p-3 text-xs text-neutral-400">
<summary className="cursor-pointer font-medium text-neutral-300">
{isThinking ? "Thinking process (generating)..." : "Reasoning process (completed)"}
</summary>
<pre className="mt-2 whitespace-pre-wrap font-mono leading-relaxed">{reasoning}</pre>
</details>
)}
{content && (
<div className="prose text-neutral-100">
{/* Main Answer: Full markdown rendering */}
{content}
</div>
)}
</div>
);
}
4. The Two Traps You Must Avoid in Production
Beyond rendering lag, two backend integration errors consistently bite engineering teams deploying DeepSeek:
Trap A: The Multi-Turn 400 Bad Request Loop
DeepSeek strictly forbids passing reasoning_content back into the API in subsequent conversation turns.
If your backend stores the entire returned assistant payload in your database and blindly forwards it as the messages array for turn 2, the API will reject your request with an HTTP 400 error. The reasoning trace belongs exclusively to the single turn in which it was generated.
// BAD: Forwarding reasoning_content crashes multi-turn
const messages = [
{ role: "user", content: "Solve x + 2 = 5" },
{ role: "assistant", reasoning_content: "Subtract 2...", content: "x = 3" }, // ❌ Causes 400
{ role: "user", content: "Now calculate x * 10" }
];
// GOOD: Strip reasoning_content before sending back
const sanitizedMessages = messages.map(msg => ({
role: msg.role,
content: msg.content
}));
Trap B: Client-Exposed API Keys
Never call https://api.deepseek.com directly from browser code. In addition to leaking your API credentials in browser network inspection tabs, browser CORS rules will block direct SSE streaming from non-whitelisted origins. Always route through a thin backend proxy (Next.js route handler, Express, or FastAPI) that streams the raw SSE response straight to the browser.
365Finds Take
The emergence of dedicated reasoning streams like DeepSeek's reasoning_content exposes how fragile our chat abstractions were. Most commercial frontends built between 2023 and 2024 assumed a chat model produces a single, monotonic stream of plain prose.
DeepSeek broke that assumption cleanly. Splitting reasoning_content from content at the protocol level is fundamentally the right engineering choice: it allows apps to audit, hide, format, or discard internal thinking without fragile string-parsing hacks like regexing <think> tags. But if you fail to throttle client state updates and sanitize multi-turn history, that same architecture will lock up your UI and poison your database.