AI › AI Tools

Streaming Ollama responses with abort handling in TanStack AI

Connect TanStack AI v1.11.0 and local Ollama to Next.js and React useChat for SSE streaming, server abort propagation, and HTTP 400 or upstream error handling.

Streaming Ollama responses with abort handling in TanStack AI

Sending production stack traces to an external LLM API is often off the table, so running a local Ollama instance behind a Next.js Route Handler is a practical alternative. This note walks through wiring @tanstack/ai@1.11.0, @tanstack/ai-react@1.3.0, and @tanstack/ai-ollama@1.1.1 with qwen2.5:1.5b for SSE streaming, client-to-server stop() abort propagation, and HTTP 400 or upstream error handling.

Verified on macOS (Apple Silicon) with Node.js 22.23.3, Next.js 15.5.29 (App Router, runtime = 'nodejs'), React 19.3.1, @tanstack/ai@1.11.0, @tanstack/ai-react@1.3.0, @tanstack/ai-ollama@1.1.1, and Ollama 0.40.18 (qwen2.5:1.5b).

Why SSE streaming and abort propagation matter for local log analysis

Spring Boot stack traces captured during an incident expose internal class paths, database table names, and transaction boundaries. Running an internal analyzer against a local Ollama server keeps those logs inside your network.

Long local generations still create a usability and resource problem. With a plain fetch that waits for the full JSON payload, the browser sits on a blank screen for seconds while the model finishes. Worse, if you paste the wrong trace and cancel on the client, the server and Ollama keep burning CPU or GPU cycles until the full response completes. Streaming over Server-Sent Events (text/event-stream) lets you read the first root-cause candidates immediately and wire browser cancellation straight into a server-side AbortController.

Streaming isn’t the right default for every request, though. Pick the transport based on who reads the output and how long generation takes.

AspectuseChat + SSE (stream: true)Single-shot JSON fetch (stream: false)
Best fitInteractive log analysis, summaries, and long responses read live by a humanBackground batch classification, webhook post-processing, short fixed replies
Time to first tokenRenders as soon as the first TEXT_MESSAGE_CONTENT delta arrivesWaits until the entire response finishes
Mid-stream cancellationstop() closes SSE and propagates through request.signal to AbortControllerHard to cancel mid-generation outside coarse timeouts
Proxy requirementsNeeds proxy buffering disabled (X-Accel-Buffering: no)Works with standard HTTP JSON proxy defaults

When a background job only needs a short label or summary, stick with stream: false and skip SSE complexity. For interactive UIs that emit hundreds of tokens, pair SSE streaming with server-side abort propagation so cancelled runs don’t pile up on a local Ollama host.

flowchart TD
    A["React useChat\n(fetchServerSentEvents)"] -->|"POST /api/analyze"| B["Next.js Route Handler\n(chatParamsFromRequest)"]
    B -->|"request.signal -> AbortController"| C["chat() + createOllamaChat\n(qwen2.5:1.5b)"]
    C -->|"TEXT_MESSAGE_CONTENT SSE"| A
    A -.->|"stop() closes connection"| B
    B -.->|"abortController.abort()"| C

Wiring Ollama streaming and AbortController in a Next.js Route Handler

The Route Handler has three jobs. First, it parses the AG-UI request payload with chatParamsFromRequest(request) and returns HTTP 400 on malformed input. Second, it forwards request.signal abort events to a fresh AbortController passed into chat(). Third, it wraps the output stream with toServerSentEventsResponse().

In @tanstack/ai@1.11.0, threadId is required on chat(). The older conversationId option from 0.x is gone, so pass params.threadId returned by chatParamsFromRequest(request).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// src/app/api/analyze/route.ts
import {
  chat,
  chatParamsFromRequest,
  toServerSentEventsResponse,
} from '@tanstack/ai'
import { createOllamaChat } from '@tanstack/ai-ollama'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

export async function POST(request: Request) {
  let params: Awaited<ReturnType<typeof chatParamsFromRequest>>
  try {
    params = await chatParamsFromRequest(request)
  } catch (err) {
    if (err instanceof Response) {
      return err
    }
    throw err
  }

  const url = new URL(request.url)
  const host = url.searchParams.get('host') || 'http://127.0.0.1:11434'
  const model = url.searchParams.get('model') || 'qwen2.5:1.5b'

  const abortController = new AbortController()
  const onAbort = () => abortController.abort()

  if (request.signal.aborted) {
    onAbort()
  } else {
    request.signal.addEventListener('abort', onAbort, { once: true })
  }

  const stream = chat({
    adapter: createOllamaChat(model, host),
    messages: params.messages,
    threadId: params.threadId,
    systemPrompts: [
      'You are a senior backend reliability engineer analyzing Spring Boot and PostgreSQL stack traces.',
      'Respond in clear, structured English with: 1) Root Cause Candidates, 2) Immediate Diagnostic Commands (SQL / JVM), and 3) HikariCP Mitigation Checklist.',
    ],
    stream: true,
    abortController,
  })

  return toServerSentEventsResponse(stream, {
    abortController,
    headers: {
      'X-Accel-Buffering': 'no',
    },
  })
}

chatParamsFromRequest(request) throws a Response instance (HTTP 400), not a plain Error, when the request body is invalid JSON or missing required AG-UI fields. Catch it and return err when err instanceof Response; otherwise Next.js turns it into an HTTP 500.

Declaring runtime = 'nodejs' and dynamic = 'force-dynamic' keeps the route on the Node.js runtime where request.signal fires abort as soon as the browser drops the SSE connection. Passing the same abortController to both chat() and toServerSentEventsResponse() stops the stream loop cleanly. The test route accepts host and model query parameters so we can inject an unreachable port during verification, but in production you should lock both values to server environment variables to avoid SSRF.

Separating streaming text, Stop control, and error banners in React useChat

On the client, build the SSE connection with fetchServerSentEvents('/api/analyze'), memoize it with useMemo, and pass it to useChat. Just like the server call, useChat requires a threadId.

Each message in messages stores structured parts instead of a flat string, so join only the parts where type === 'text'. Tracking a local abortedManually flag also lets the UI distinguish a user-triggered stop() from a completed response or a network failure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// src/app/log-analyzer/page.tsx (core excerpt)
'use client'

import { useMemo, useState } from 'react'
import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'

function extractText(
  parts: ReadonlyArray<{ type: string; content?: string }>,
): string {
  return parts
    .filter((p) => p.type === 'text' && typeof p.content === 'string')
    .map((p) => p.content)
    .join('')
}

export default function LogAnalyzerPage() {
  const [logInput, setLogInput] = useState(SAMPLE_STACK_TRACE)
  const [abortedManually, setAbortedManually] = useState(false)
  const [deltaCount, setDeltaCount] = useState(0)

  const connection = useMemo(
    () => fetchServerSentEvents('/api/analyze'),
    [],
  )

  const { messages, sendMessage, stop, clear, isLoading, error } = useChat({
    threadId: 'log-analyzer-local',
    connection,
    onChunk: (chunk) => {
      if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
        setDeltaCount((c) => c + 1)
      }
    },
  })

  const latestAssistant = [...messages]
    .reverse()
    .find((m) => m.role === 'assistant')
  const assistantText = latestAssistant
    ? extractText(latestAssistant.parts as Array<{ type: string; content?: string }>)
    : ''

  const handleAnalyze = async () => {
    setAbortedManually(false)
    setDeltaCount(0)
    clear()
    await sendMessage(`Analyze this production stack trace:\n\n${logInput}`)
  }

  const handleStop = () => {
    setAbortedManually(true)
    stop()
  }

  return (
    <section>
      <button type="button" onClick={handleAnalyze} disabled={isLoading || !logInput.trim()}>
        Analyze Log
      </button>
      <button type="button" onClick={handleStop} disabled={!isLoading}>
        Stop Generation
      </button>

      {error && (
        <div role="alert">
          <strong>Stream Error:</strong> {error.message}
        </div>
      )}

      {abortedManually && !isLoading && !error && (
        <div>
          <strong>Generation Aborted:</strong> Client called <code>stop()</code>;
          partial response preserved and server <code>request.signal</code> aborted.
        </div>
      )}

      <pre>{assistantText}</pre>
    </section>
  )
}

The onChunk callback lets you inspect incoming AG-UI events as they arrive. Counting TEXT_MESSAGE_CONTENT chunks makes streaming progress visible in the UI without parsing raw SSE frames yourself. Guarding the aborted banner with !error ensures an upstream failure always renders the error state instead of looking like a manual stop.

Observed streaming, mid-stream abort, and error behavior

I ran three checks against a live local Ollama server (http://127.0.0.1:11434, qwen2.5:1.5b) using a Spring Boot HikariCP pool-exhaustion stack trace (HikariPool-1 - Connection is not available, request timed out after 30000ms (total=10, active=10, idle=0, waiting=24), caused by a PostgreSQL lock timeout on settlement_ledger).

1. Live SSE streaming

Clicking Analyze Log returned HTTP 200 with Content-Type: text/event-stream and rendered tokens incrementally before completion. A mid-stream snapshot showed 26 deltas (125 characters), and the completed run accumulated 655 TEXT_MESSAGE_CONTENT deltas (2,757 characters) before switching to Completed.

Local Error Log Analyzer mid-stream showing Streaming SSE badge, isLoading true, 30 deltas, and an active Stop Generation button Figure 1. Live SSE stream against local Ollama qwen2.5:1.5b showing Streaming SSE, isLoading: true, deltas: 30, and the active Stop Generation button.

2. Mid-stream stop() and server AbortController propagation

On a second run, clicking Stop Generation after 27 deltas switched the client immediately to isLoading: false and status: ready while keeping the 117 characters already rendered on screen.

Local Error Log Analyzer after calling stop() showing Aborted by User badge, isLoading false, 27 deltas, and the preserved partial response Figure 2. State right after calling stop() at 27 deltas. The 117-character partial answer stays visible under the Aborted by User banner.

Checking the server Route Handler event log for that run confirmed that request_signal_aborted fired 199ms after request_started, flipping abortController.signal.aborted to true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[
  {
    "timestamp": "2026-12-02T13:59:51.139Z",
    "runId": "run-1796219991137-itkcq7",
    "event": "request_started",
    "abortControllerAborted": false,
    "detail": "host=http://127.0.0.1:11434 model=qwen2.5:1.5b"
  },
  {
    "timestamp": "2026-12-02T13:59:51.338Z",
    "runId": "run-1796219991137-itkcq7",
    "event": "request_signal_aborted",
    "abortControllerAborted": true,
    "detail": "request.signal fired abort"
  }
]

3. HTTP 400 bad request bodies and upstream failure

Sending broken JSON or a payload missing required fields to /api/analyze returned HTTP 400 directly from chatParamsFromRequest(request).

1
2
3
curl -sS -i -X POST http://127.0.0.1:3199/api/analyze \
  -H 'Content-Type: application/json' \
  -d '{"messages": [BROKEN_JSON'
1
2
3
HTTP/1.1 400 Bad Request
...
Invalid AG-UI request body. See docs/migration/ag-ui-compliance.md.

Switching the analyzer target to an unreachable local port (http://127.0.0.1:19999) populated useChat’s error state with fetch failed, set isLoading to false, and surfaced the red error banner instead of hanging.

Local Error Log Analyzer showing Error badge, isLoading false, 0 deltas, and Stream Error fetch failed banner for unreachable port 19999 Figure 3. Requesting an unreachable Ollama port (:19999) populates useChat error with fetch failed and resets isLoading to false.

ScenarioTest inputObserved outcome
Live SSE streamingLocal Ollama qwen2.5:1.5b (:11434), HikariCP traceHTTP 200 text/event-stream, mid-stream 26 deltas (125 chars) → final 655 deltas (2,757 chars), Completed
Mid-stream stop()Click Stop Generation at 27 deltasisLoading: false, 117 chars preserved, server logged request_signal_aborted (abortControllerAborted: true) within 199ms
Malformed request bodyBroken JSON / missing fields to POST /api/analyzeHTTP 400, Invalid AG-UI request body...
Upstream failureUnreachable host (127.0.0.1:19999)useChat error set to fetch failed, isLoading: false, status: error

Production caveats and checklist

SSE streaming and abort signals work reliably on a local Node.js server, but deployment layers can silently break both if left at defaults.

  • Disable reverse-proxy buffering: Nginx and ingress controllers often buffer responses until completion, hiding streaming entirely. Keep X-Accel-Buffering: no in the Route Handler response headers, set proxy_buffering off, and raise proxy_read_timeout to cover long generations.
  • Pin Ollama host and model on the server: Never let query parameters or request bodies choose the upstream URL in production. Read the Ollama host and allowed model list from server-side configuration.
  • Scope threadId to authenticated sessions: Namespace threadId per user or workspace and verify ownership on the server before running chat().
  • Cap concurrent local inferences: A single Ollama host queues quickly under parallel requests. Enforce a per-user concurrency limit in the Route Handler and verify that stop() propagates abort so cancelled runs release model slots promptly.

Abort propagation here was verified on a single local Next.js Node.js process (runtime = 'nodejs'). If you deploy on serverless or Edge runtimes, or behind an API gateway, test that client disconnects actually trigger request.signal abort in your target environment.

References

Add a streaming TanStack AI chat to your app. Pick a framework, install, stream from a server route, and render with the matching hook.
Run local open models with Ollama in TanStack AI with @tanstack/ai-ollama. No API key, no API cost, and your data stays on your hardware.
Pick how your chat gets chunks from the server to useChat: SSE, HTTP stream, JSON, WebSockets, React Native, server functions, or your own transport.
This post is licensed under CC BY 4.0 by the author.