Skip to content

MiddlewareBase classes

Reusable middleware as classes with before, after, and finally hooks, static provides, and response helpers.

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

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();
MemberRequired?Purpose
static depsYesServices this middleware may inject() ([] if none)
static stateYesState tokens this middleware reads ([] if none)
static providesOptionalState tokens written in before()
static configOptionalConfig tokens this middleware may read

Registration throws at call time if deps or state is missing. Missing lifecycle hooks throw at host.build().

MemberDescription
this.ctxFlareHttpContext 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:

MethodSignature
before()MiddlewareOverride | Promise<MiddlewareOverride>
after(result)MiddlewareOverride | Promise<MiddlewareOverride>
finally(result)MiddlewareOverride | Promise<MiddlewareOverride>

Protected helpers on MiddlewareBase for short-circuiting from before():

MethodStatus
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.