MiddlewareBase classes
Reusable middleware as classes with before, after, and finally hooks, static provides, and response helpers.
AI generated, pending review
MiddlewareBase extends FlareBase and mirrors controller composition. Register with host.http.use(Cls) or g.use(Cls) inside a group. At host.build(), the class must implement at least one of before(), after(), or finally().
import { MiddlewareBase, FlareHost, flareState, Logger,} from "@flare-ts/core";import { node } from "@flare-ts/core/node";
const AuthUser = flareState<{ id: string }>("AuthUser");
class AuthMiddleware extends MiddlewareBase { public static override deps = [Logger]; public static override state = []; public static override provides = [AuthUser];
before() { const token = this.ctx.req.headers.get("authorization"); if (!token) return this.unauthorized({ error: "missing token" }); this.ctx.state.set(AuthUser, { id: "u1" }); }
finally() { this.inject(Logger).info("request done", { user: this.ctx.state.get(AuthUser)?.id ?? null, }); }}
const host = new FlareHost(node);host.http.use(AuthMiddleware);
host.http.get("/me", { state: [AuthUser] }, (ctx) => { return { id: ctx.state.require(AuthUser).id };});
const app = host.build();app.run();Required static members
Section titled “Required static members”| Member | Required? | Purpose |
|---|---|---|
static deps | Yes | Services this middleware may inject() ([] if none) |
static state | Yes | State tokens this middleware reads ([] if none) |
static provides | Optional | State tokens written in before() |
static config | Optional | Config tokens this middleware may read |
Registration throws at call time if deps or state is missing. Missing lifecycle hooks throw at host.build().
Instance API
Section titled “Instance API”| Member | Description |
|---|---|
this.ctx | FlareHttpContext for the current request |
this.inject(token) | Resolve a service from static deps |
this.config(token) | Resolve a config token from static config |
Optional lifecycle methods:
| Method | Signature |
|---|---|
before() | MiddlewareOverride | Promise<MiddlewareOverride> |
after(result) | MiddlewareOverride | Promise<MiddlewareOverride> |
finally(result) | MiddlewareOverride | Promise<MiddlewareOverride> |
Response helpers
Section titled “Response helpers”Protected helpers on MiddlewareBase for short-circuiting from before():
| Method | Status |
|---|---|
badRequest(body) | 400 |
unauthorized(body) | 401 |
forbidden(body) | 403 |
notFound(body) | 404 |
tooManyRequests(body) | 429 |
error(body) | 500 |
Read request data from this.ctx.req. There is no this.req.
Related
Section titled “Related”- Inline middleware
- Middleware that provides state: auth pattern walkthrough
- Middleware overview: group
excludeandreplace