Add to an existing app
Flow State can live inside an app you already run. The AI part is a flow: a self-contained piece of backend with named actions. Your app calls them over HTTP, so nothing you have needs to move. You add three things: a flow, a server for it, and a page that calls it.
This page adds one flow, support, with one action, reply. It needs Next.js 15 or later with the App Router, and Node 22 or later. The Pages Router is not supported.
Install the packages
pnpm add @flow-state-dev/core @flow-state-dev/engine @flow-state-dev/next @flow-state-dev/react zod @ai-sdk/openai
Put OPENAI_API_KEY in .env.local and keep that file out of git. Environment variables has the key and package for Anthropic and Google.
Write one flow
import { defineFlow, generator } from "@flow-state-dev/core";
import { z } from "zod";
const replyInput = z.object({ message: z.string().min(1) });
const reply = generator({
name: "reply",
model: "openai/gpt-6-luna",
prompt: "You answer support questions briefly.",
inputSchema: replyInput,
history: true,
user: (input) => input.message,
itemVisibility: { client: true, history: true },
});
const supportFlow = defineFlow({
kind: "support",
actions: {
reply: { block: reply, userMessage: (input) => input.message },
},
});
export default supportFlow();
reply is a generator, a block that calls a model. With no output schema it replies in text that streams, history: true gives it the earlier turns, and itemVisibility sends its reply to the browser and keeps it in the transcript. Generators has the details. userMessage makes the user's own line appear in the transcript too. kind names the flow, and Flows lists its other fields.
Serve it
fsdev.config.ts builds the server from a list of flows.
import { createFlowState } from "@flow-state-dev/engine";
import support from "./src/flows/support/flow";
export default createFlowState({ flows: [support] });
A session is the record that keeps one user's requests together. With no stores, sessions live in memory and are lost on restart. Serving flows covers keeping them, and every other option.
A route file mounts it in Next.js.
import { createNextHandler } from "@flow-state-dev/next";
import flowstate from "../../../../../fsdev.config";
export const dynamic = "force-dynamic";
export const { GET, POST, PATCH, DELETE } = createNextHandler(flowstate, {
allowUnauthenticated: process.env.ALLOW_UNAUTHENTICATED === "true",
});
The flow has no sign-in yet, so the handler refuses every request until the flow checks who is calling: Auth and tenancy. To try it on your own machine, set the variable the route reads. ALLOW_UNAUTHENTICATED is this app's own name, not a Flow State setting.
ALLOW_UNAUTHENTICATED=true
next dev listens on every network interface, so while the variable is set, anyone who can reach the dev server can call the flow as any user. Set it only on a machine nobody else can reach, and never in a deployment.
One route file serves every flow under /api/flows. A second flow is one more entry in flows.
No Next.js app? Run pnpm add @flow-state-dev/node. It starts a long-lived HTTP server for the same config.
import { serve } from "@flow-state-dev/node";
import flowstate from "../fsdev.config";
await serve(flowstate, { host: "127.0.0.1" });
serve binds every network interface unless you pass host. On any host but loopback it refuses to start while a flow has no way to check who is calling (authentication.resolvePrincipal), so this one binds 127.0.0.1. It does not read .env.local, so start it with the file loaded:
npx tsx --env-file=.env.local src/server.ts
Call it from a page
"use client";
import { useState } from "react";
import { FlowProvider, ItemsRenderer, useFlow, useSession } from "@flow-state-dev/react";
export default function Page() {
return (
<FlowProvider flowKind="support" userId="u1">
<Support />
</FlowProvider>
);
}
function Support() {
const flow = useFlow({ autoCreateSession: true });
const session = useSession(flow.activeSessionId);
const [text, setText] = useState("");
return (
<main>
<ItemsRenderer items={session.items} />
{session.error && <p role="alert">{session.error.message}</p>}
<form
onSubmit={(e) => {
e.preventDefault();
session.sendAction("reply", { message: text }).then(
() => setText(""),
() => {}, // kept in session.error, and the text stays for a retry
);
}}
>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button disabled={!session.canSendAction || !flow.activeSessionId}>Send</button>
</form>
</main>
);
}
useFlow finds the user's newest session, or creates one, and gives back its id. The id is empty on the first render, so the button waits for it. session.items is the transcript, in order, and ItemsRenderer draws it with plain defaults. sendAction resolves when the request is accepted, and the answer arrives in items. If the request is refused, it rejects and session.error holds why, so the form clears the text only on success.
Every call says who is calling. The provider's userId goes with each request, and a call without one is refused. With no sign-in configured, the server believes whatever userId the request carries, so a setup like this one is only for development. Only serve() and fsdev dev on a loopback host serve it without an override. The Next.js, Vercel and Lambda handlers refuse every request unless given allowUnauthenticated: true. Auth and tenancy covers verifying callers.
Common pitfalls
- The page stays empty. The generator has no
itemVisibility, so it emits nothing for the page to show. Set{ client: true, history: true }: Items and the stream. - The reply arrives all at once. Next.js buffers the response unless the route file exports
dynamic = "force-dynamic": HTTP API. - Streaming and state calls fail. The route file must export all four verbs,
GET,POST,PATCHandDELETE, and the stream is read withGET: HTTP API. /api/flowsreturns 404. The route folder must be named[[...path]], with double brackets, so the bare/api/flowsis served: HTTP API.- A hook errors in a server component. Hooks run only in client components, so put
"use client"at the top of the file: Client configuration. - Requests go to
/api/api/flows. The client adds/api/flowsitself, so abaseUrlof/apidoubles the prefix. On the same origin, leavebaseUrloff: Client configuration. createNextHandlerrejects the router. It takes the objectcreateFlowStatereturned, notflowstate.getRouter(): Runtime options.
Next
- Serving flows covers
stores, models and the other ways in. - What the browser sees has the hooks, and how to draw your own items.
- Auth and tenancy is what to set before anyone else can reach the route.
- Choose where to deploy puts it on Vercel or a long-lived host.
- Runtime options lists every option on
createFlowState.