State and scopes
State is typed data your app keeps on the server so that one step can use what an earlier one worked out: a customer's plan, a count of tickets, a setting an admin chose. You declare its shape with a Zod schema and read and write it from the code that runs a step. Flow State keeps it in four places, called scopes, and they differ in how long the data lasts and who shares it.
The example is a support desk, a flow named support: a self-contained system inside your app that a client calls by action name. A session is where a flow keeps a run of requests together, here one customer conversation.
Request state is scratch space for one run, such as a retry count, tries. A second request cannot read what the first put there. A block declares it with requestStateSchema.
Session first
Most state belongs to the session: if the next request might care, put it there. A block declares the fields it touches with a schema; you don't declare them again on the flow. A field's default is what a new session reads.
The block reads and writes it through ctx, the object every block receives, and ctx.session.state is typed from the schema. countTicket runs inside handleTicket, the flow's action, which is what a client calls.
import { handler } from "@flow-state-dev/core";
import { z } from "zod";
export const countTicket = handler({
name: "count-ticket",
inputSchema: z.object({ message: z.string() }),
outputSchema: z.object({ first: z.boolean() }),
sessionStateSchema: z.object({ ticketCount: z.number().default(0) }),
execute: async (_input, ctx) => {
const before = ctx.session.state.ticketCount;
await ctx.session.incState({ ticketCount: 1 });
return { first: before === 0 };
},
});
incState adds to a number. patchState merges fields into the state instead. State is read-only on ctx; you change it through these calls. The next request with the same session id reads the count the last one left, and a new session starts again at 0. State operations lists every call and what it returns.
A session belongs to one user in one organization, fixed when it is created.
State a user carries between conversations
The customer's plan should follow them into every conversation, so it is user state. Declare it on a block the same way, with userStateSchema: a plan that defaults to "free" and an internal score that defaults to 0. Org state takes orgStateSchema, here a licenses field that defaults to 5.
import { handler } from "@flow-state-dev/core";
import { z } from "zod";
export const upgradePlan = handler({
name: "upgrade-plan",
inputSchema: z.object({ plan: z.string() }),
outputSchema: z.object({ plan: z.string(), licenses: z.number().optional() }),
userStateSchema: z.object({
plan: z.string().default("free"),
score: z.number().default(0),
}),
orgStateSchema: z.object({ licenses: z.number().default(5) }),
execute: async (input, ctx) => {
await ctx.user.patchState({ plan: input.plan });
return { plan: input.plan, licenses: ctx.org?.state.licenses };
},
});
The calls are the same as for the session. Only the scope changes. ctx.org is typed as optional, so read it with ?.. When a customer, Alice, upgrades to "pro", a brand-new session of hers reads plan as "pro". A user's state belongs to them inside one organization: Alice in another organization reads "free", and so does Bob, who shares her organization but not her user record. How flows share or keep apart a user's record is in the flows reference.
State an organization shares
Org state is for what everyone in an organization uses, such as settings an admin controls. Where the organization comes from is Auth and tenancy.
Two users in one organization share the org record and nothing else. When Alice sets licenses to 9, Bob reads 9. His plan and his sessions stay his.
What the browser may see
The browser's client data never holds raw state. Only the fields you name in a scope's client.expose appear in it, so an internal score stays out by being left out. A change to an unexposed field can pass through the stream while a request runs, so expose is not a way to keep secrets. Request state cannot be exposed at all.
Exposure is set on the flow. handleTicket, the flow's action, is a sequencer that runs countTicket and upgradePlan, each in its own file beside the flow. The flow exposes plan:
import { defineFlow } from "@flow-state-dev/core";
import { handleTicket } from "./blocks/handle-ticket";
export const supportFlow = defineFlow({
kind: "support",
actions: { handleTicket },
user: { client: { expose: ["plan"] } },
});
export default supportFlow();
A component then asks for it by name. The values come back untyped, hence the String.
"use client";
import { useClientData, useSession } from "@flow-state-dev/react";
export function PlanBadge({ sessionId }: { sessionId: string }) {
const session = useSession(sessionId, { flowKind: "support" });
const data = useClientData(session, { user: ["plan"] });
return <span>{String(data.user.plan)}</span>;
}
Blocks on the server can read and write score. A value computed from state is a view, not an exposed field.
What it gets you
- Typed state on the server.
ctx.session.state.ticketCountis anumber, and writing a string to it is a compile error. - A lifetime picked by where the field goes.
trieslasts one run,ticketCountone conversation,planone customer andlicensesone organization. - No filtering code. A customer in two organizations has two user records, so no block writes
where orgId = .... - New fields need no migration. A field added with a default reads that default on every record saved before it existed.
- Client data holds only what you name. Adding a field to a schema does not put it in
useClientData. Onlyexposedoes.
How it fits with the others
State is typed data on a scope. A resource is a named container of structured data with a scope of its own. A session's items, the messages and tool calls it records, sit beside its state and are not part of it; Sessions, items and streaming covers them.
Next
- State operations lists every call on
ctx.session,ctx.userandctx.org, what each returns and what happens when two requests write at once. - Views shows how to send the browser a value computed from state.
- Auth and tenancy covers where the user and organization come from.
- Flows reference lists the isolation settings and every field of a scope's config.