Skip to content

Reading state

Read and write per-request state with ctx.state.get, require, and set - frozen snapshots and resolution order.

AI generated, pending review Updated 10 days ago · Flare 0.3

ctx.state is the per-request store on FlareHttpContext. Middleware writes with set; handlers read with get or require.

CallReturnsThrows if missing?
ctx.state.require(token)DeepReadonly<T> (frozen)Yes
ctx.state.get(token)DeepReadonly<T> or undefinedNo
ctx.state.set(token, value)voidNo at set time

Reads always return frozen snapshots. Mutating the returned object does not change stored state.

  1. Stored value from set
  2. .from() derivation
  3. .withDefault() fallback
  4. undefined
import { FlareHost, FlareResponse, flareState } from "@flare-ts/core";
import { node } from "@flare-ts/core/node";
const AuthUser = flareState<{ id: string }>("AuthUser");
const host = new FlareHost(node);
host.http.get(
"/me",
{ state: [AuthUser] },
(ctx) => new FlareResponse(200, ctx.state.require(AuthUser)),
);
const app = host.build();
app.run();
import { ControllerBase, flareState } from "@flare-ts/core";
import { Get } from "@flare-ts/core/decorators";
const AuthUser = flareState<{ id: string }>("AuthUser");
class MeController extends ControllerBase {
public static override deps = [];
public static override state = [AuthUser];
@Get("")
me() {
return this.ok(this.ctx.state.require(AuthUser));
}
}

Use get when the token is optional:

const maybe = ctx.state.get(AuthUser);
if (maybe === undefined) { /* ... */ }

ctx.state.set(token, value) does not check provides at runtime. HTTP compile compares each consumer’s state list against middleware provides instead.

Values are deep-frozen on write. Primitives, plain objects, and arrays are supported; class instances and circular structures throw.

If .from() handlers mutually require each other, the read that closes the cycle throws with a circular-derivation message.