Next.js and the AI SDK
A Next.js App Router chat whose answers are Typst documents, streamed with the Vercel AI SDK's streamText and useChat and rendered with the Typstream component, with @typstream/ai reading each answer.
This page builds a chat where the model answers in Typst and every answer renders as a live document. A route handler streams the model's text with streamText, useChat receives it on the client, and each assistant message goes into its own <Typstream>, with @typstream/ai reading its text and whether it's still being written.
It's written against Next.js 16, AI SDK 7 (ai), @ai-sdk/react 4 and @ai-sdk/anthropic 4. examples/nextjs-ai-sdk in the repository is the finished version: the same chat with edu's prompt kit and plugin, answers as pages, telemetry, and a chat UI from shadcn/ui's AI Elements.
Install
npm install typstream @typstream/ai ai @ai-sdk/react @ai-sdk/anthropicSet ANTHROPIC_API_KEY in .env.local. Any AI SDK provider works the same way.
The route handler
The server asks the model for a Typst document and streams the reply as a UI message stream. The instructions matter: models default to Markdown, and the healer can only fix so much of it.
import { anthropic } from "@ai-sdk/anthropic";
import { convertToModelMessages, streamText, type UIMessage } from "ai";
export const maxDuration = 60;
const INSTRUCTIONS = `You write educational documents (worksheets, quizzes, handouts) in Typst 0.15 markup.
Reply with the Typst source only: no Markdown, no code fences, no commentary before or after.
- Headings are "= Title", "== Section"; *bold*, _italic_; "- " bullets and "+ " numbered items.
- Math goes between dollar signs: $a^2 + b^2 = c^2$, with a space inside for display math: $ x = 1/2 $.
- Tables: #table(columns: 3, [Header], [Header], [Header], [cell], [cell], [cell]).
- Write a literal dollar sign, hash or at sign as \\$, \\#, \\@.
- Leave room for answers with #v(2em) or #line(length: 100%).
- Leave the page size to the viewer: no paper, width, height or flipped in #set page (margins are fine).`;
export async function POST(request: Request) {
const { messages }: { messages: UIMessage[] } = await request.json();
const result = streamText({
model: anthropic("claude-sonnet-5-5"),
instructions: INSTRUCTIONS,
messages: await convertToModelMessages(messages),
});
return result.toUIMessageStreamResponse();
}In AI SDK 7, instructions is the system prompt (system still works but is deprecated).
The chat page
The page is a client component: useChat holds the messages and posts to /api/chat, and each assistant message renders as a <Typstream>.
"use client";
import { useChat } from "@ai-sdk/react";
import { isStreaming, textOf } from "@typstream/ai";
import { useState } from "react";
import { Typstream } from "typstream";
export default function Page() {
const chat = useChat();
const { messages, sendMessage, status } = chat;
const [input, setInput] = useState("");
const busy = status === "streaming" || status === "submitted";
return (
<main>
{messages.map((message) =>
message.role === "user" ? (
<p key={message.id}>{textOf(message)}</p>
) : (
<Typstream
key={message.id}
source={textOf(message)}
isStreaming={isStreaming(message, chat)}
animated
caret
/>
),
)}
<form
onSubmit={(e) => {
e.preventDefault();
if (!input.trim() || busy) return;
void sendMessage({ text: input });
setInput("");
}}
>
<input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Ask for a worksheet…" />
<button type="submit" disabled={busy}>
Send
</button>
</form>
</main>
);
}Run npm run dev and ask for "A one-page worksheet on the Pythagorean theorem for grade 8".
How it fits together
- One
<Typstream>per assistant message.textOf(message)is the message's text so far (its text parts; reasoning and tool parts aren't the document), which is whatsourceexpects. Key it by the message's id, so React keeps each document's component (and its rendered output) across updates. isStreaming(message, chat)only for the answer being written. It's true while the chat answers with this message and its text hasn't ended (text followed by a tool call hasn't: more may come). Both halves matter:status === "streaming"is true for the whole chat while any answer streams, so every earlier answer would go back to streaming and start over; and a text part's ownstatestays"streaming"when the user stops the answer or the network fails, so that document would never finish. When it turns false, the answer is compiled in final mode and the caret disappears.- One worker for the whole chat. Every
<Typstream>shares one engine worker, and only answers near the viewport or still streaming compile. A long conversation stays cheap. "use client".useChatalready makes the page a client component. Thetypstreambundle is marked"use client"itself, so you can also render<Typstream>from a Server Component with a fixedsource. On the server it renders an empty<div>; the document appears in the browser.- No Next.js configuration. The engine's worker, the wasm and the fonts are
new URL(…, import.meta.url)assets that Turbopack and webpack emit. The example'snext.config.tssets onlyturbopack.root, because it lives in a pnpm monorepo whose packages are symlinked from outside the app; a standalone app doesn't need it.
Follow-ups
Once there's a document, the teacher's next request usually changes it ("make question 3 harder"). The example
answers it with a new document: edu's prompt kit asks for the whole document in every answer, and the earlier answers
are in the chat. The route sends the chat to the model exactly as useChat posted it, with the same system prompt
every time. Don't rewrite earlier messages (to add the current document to them, say): with Claude's extended
thinking, an answer's thinking is signed over everything before it, and a request in which that changed fails.
Streaming edits changes the document in place instead.
Show progress under each answer
useTypstream() reads one document's state. Move the <Typstream> into its own component to show a status line under each answer:
"use client";
import { Typstream, useTypstream } from "typstream";
export function Answer({ text, streaming }: { text: string; streaming: boolean }) {
const t = useTypstream();
const frame = t.openFrames[0]?.frame;
return (
<article>
<Typstream ref={t.ref} source={text} isStreaming={streaming} layout="fit-width" animated caret />
<footer>
{t.status}
{streaming && frame ? ` · writing ${frame}…` : ""}
{t.diagnostics.length ? ` · ${t.diagnostics.length} diagnostics` : ""}
</footer>
</article>
);
}layout="fit-width" only applies to the paged target (target="paged"): it scales the document's pages to the answer's width, so they are the pages its PDF has. The example has a switch between the HTML and paged targets.
Better prompts with the edu plugin
The instructions above are short. For worksheets, quizzes and exams, @typstream/edu gives the model a vocabulary (#question, #mcq, #blank, answer keys) and buildSystemPrompt writes the system prompt for it: Typst rules that target the mistakes models actually make, each function's signature and example, and example documents.
Beta
buildSystemPrompt is @beta: its output and options may change before 1.0.
import { buildSystemPrompt, edu } from "@typstream/edu";
import { universe } from "@typstream/universe";
const INSTRUCTIONS = buildSystemPrompt([edu, universe]); // deterministic, so it cachesImport universe from @typstream/universe here, not from typstream: the typstream bundle is a client module. Then render with the same plugin on the client, so the functions the model was told about exist:
import { edu } from "@typstream/edu";
<Typstream source={textOf(message)} isStreaming={isStreaming(message, chat)} plugins={[edu]} animated caret />;Prompting covers the prompt kit, and Telemetry shows how the example wires typstream's events to an analytics endpoint with <TypstreamProvider>.