Middleware class abstract
Runs before a route's controller.
There are two ways to write one.
Override handle when the middleware only inspects or augments the request, and rejects by throwing. This is the common case:
class RequireApiKey extends Middleware {
@override
Future<void> handle(Request req) async {
if (req.header('x-api-key') != expected) {
throw Unauthenticated(message: 'Bad key');
}
}
}
Override process when the middleware needs to do something after the rest of the chain runs — timing, logging, adding a header that depends on the response — or to skip the chain entirely:
class Timing extends Middleware {
@override
Future<void> process(Request req, Next next) async {
final started = DateTime.now();
await next();
final ms = DateTime.now().difference(started).inMilliseconds;
req.response.headers.add('X-Duration-Ms', '$ms');
}
}
Not calling next() stops the chain: no later middleware runs and the
controller is not invoked. The middleware is then responsible for the
response.
Overriding both is a mistake — process wins and handle is ignored.
- Implementers
Constructors
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
handle(
Request req) → Future< void> - Inspect or reject the request. Throw to abort the chain.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
process(
Request req, Next next) → Future< void> - Wraps the rest of the chain.
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited