Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

quick-start-server.md

184 lines5.3 KB

1---
2title: "Quick Start: Server Only"
3id: quick-start-server
4order: 5
5description: "Add a streaming AI chat endpoint to a Node.js backend with TanStack AI — no UI framework required."
6keywords:
7 - tanstack ai
8 - node.js
9 - server
10 - backend
11 - quick start
12 - streaming chat
13 - openai
14 - sse
15---
16​
17You have a Node.js backend and want to add AI capabilities. By the end of this guide, you'll have a working chat endpoint powered by TanStack AI and OpenAI -- no UI framework required.
18​
19> **Tip:** If you'd prefer not to sign up with individual AI providers, [OpenRouter](../adapters/openrouter) gives you access to 300+ models with a single API key and is the easiest way to get started.
20​
21## Installation
22​
23<!-- ::start:tabs variant="package-manager" mode="install" -->
24​
25react: @tanstack/ai @tanstack/ai-openai
26vue: @tanstack/ai @tanstack/ai-openai
27solid: @tanstack/ai @tanstack/ai-openai
28svelte: @tanstack/ai @tanstack/ai-openai
29preact: @tanstack/ai @tanstack/ai-openai
30angular: @tanstack/ai @tanstack/ai-openai
31vanilla: @tanstack/ai @tanstack/ai-openai
32octane: @tanstack/ai @tanstack/ai-openai
33​
34<!-- ::end:tabs -->
35​
36## Basic Chat
37​
38The simplest way to get a response -- call `chat()` and collect the text:
39​
40```typescript
41import { chat, streamToText } from '@tanstack/ai'
42import { openaiText } from '@tanstack/ai-openai'
43​
44const stream = chat({
45 adapter: openaiText('gpt-5.5'),
46 messages: [{ role: 'user', content: 'Hello!' }],
47})
48​
49const text = await streamToText(stream)
50console.log(text)
51```
52​
53`chat()` returns an `AsyncIterable<StreamChunk>`. `streamToText` consumes it and returns the accumulated text content.
54​
55## HTTP Endpoint
56​
57Here's an Express server that exposes a streaming chat endpoint using Server-Sent Events:
58​
59```typescript ignore
60import express from 'express'
61import { chat, toServerSentEventsResponse } from '@tanstack/ai'
62import { openaiText } from '@tanstack/ai-openai'
63​
64const app = express()
65app.use(express.json())
66​
67app.post('/api/chat', async (req, res) => {
68 const { messages } = req.body
69​
70 const stream = chat({
71 adapter: openaiText('gpt-5.5'),
72 messages,
73 })
74​
75 const response = toServerSentEventsResponse(stream)
76 res.writeHead(response.status, Object.fromEntries(response.headers))
77​
78 const body = response.body
79 if (body) {
80 const reader = body.getReader()
81 const pump = async () => {
82 const { done, value } = await reader.read()
83 if (done) {
84 res.end()
85 return
86 }
87 res.write(value)
88 await pump()
89 }
90 await pump()
91 }
92})
93​
94app.listen(3000, () => console.log('Server running on port 3000'))
95```
96​
97> **Tip:** Any backend that returns the TanStack AI SSE format works -- you can use Fastify, Hono, or any other Node.js framework.
98​
99This endpoint is compatible with TanStack AI's client-side `useChat` hooks (`@tanstack/ai-react`, `@tanstack/ai-vue`, `@tanstack/ai-svelte`), so you can pair it with any frontend later.
100​
101## With Tools
102​
103Define a server tool with `toolDefinition` and pass it to `chat()`. The agent loop automatically calls your tool and feeds the result back to the model:
104​
105```typescript
106import { chat, toolDefinition, streamToText } from '@tanstack/ai'
107import { openaiText } from '@tanstack/ai-openai'
108import { z } from 'zod'
109​
110const getWeather = toolDefinition({
111 name: 'getWeather',
112 description: 'Get weather for a city',
113 inputSchema: z.object({ city: z.string() }),
114 outputSchema: z.object({ temp: z.number(), condition: z.string() }),
115}).server(async ({ city }) => {
116 return { temp: 22, condition: 'sunny' }
117})
118​
119const stream = chat({
120 adapter: openaiText('gpt-5.5'),
121 messages: [{ role: 'user', content: 'Weather in Tokyo?' }],
122 tools: [getWeather],
123})
124​
125const text = await streamToText(stream)
126console.log(text)
127```
128​
129The model decides when to call `getWeather`, receives the result, and incorporates it into its response -- all within a single `chat()` call.
130​
131## Alternative Response Formats
132​
133TanStack AI ships several ways to return a stream over HTTP:
134​
135**`toHttpResponse()`** returns a `Response` using newline-delimited JSON instead of SSE. Pair it with `fetchHttpStream` on the client:
136​
137```typescript
138import { chat, toHttpResponse } from '@tanstack/ai'
139import { openaiText } from '@tanstack/ai-openai'
140​
141export async function POST(request: Request) {
142 const { messages } = await request.json()
143 const stream = chat({
144 adapter: openaiText('gpt-5.5'),
145 messages,
146 })
147 return toHttpResponse(stream)
149```
150​
151**Raw stream consumption** -- iterate the `AsyncIterable` directly with `for await`:
152​
153```typescript
154import { stream } from './stream'
155​
156for await (const chunk of stream) {
157 if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
158 process.stdout.write(chunk.delta ?? '')
159 }
161```
162​
163This gives you full control over every chunk type (text deltas, tool calls, run lifecycle events, etc.).
164​
165## Environment Variables
166​
167Create a `.env` file with your API key:
168​
169```bash
170# OpenRouter (recommended — access 300+ models with one key)
171OPENROUTER_API_KEY=sk-or-...
172​
173# OpenAI
174OPENAI_API_KEY=your-openai-api-key
175```
176​
177The adapter reads `OPENAI_API_KEY` at runtime. Never expose it to the browser.
178​
179## Next Steps
180​
181- Learn about [Tools](../tools/tools) to add function calling and agent loops
182- Explore [StreamProcessor](../reference/classes/StreamProcessor) for fine-grained stream control
183- Check out the [Adapters](../adapters/openai) to connect to different providers
184- See the [Quick Start](./quick-start) to add a frontend