shelf_router only shows how you add middleware for the whole app, but we need route-based middleware.
Here is how you do it, an example with an authentication mechanism;
Some request to -> sayhi
authenticationMiddleware checks if the user has a session
authenticationMiddleware returns Response.forbidden if there is no session and prevent calling ‘sayhi’ handler
authenticationMiddleware adds the user object to Request Context if there is a session and calls ‘sayhi’ handler.
sayhi handler can be sure there is a user
var app = Router();app.get(“/sayhi”, (Request request) => authenticationMiddleware(request, AuthController().sayhi));Future<Response> authenticationMiddleware(Request request, Handler next) async {
// check user token.
final user // find user from DB or check JWT.
if (user == null) {
return Response.forbidden(“You have no permission.”);
} // we are creating a new Request object since Context object is immutable and we are not able to add its data.
Request r = request.change(context: {“user”: user});
return next(r);
}Future<Response> sayhi(Request request) async {
print(request.context[“user”]);
return Response.ok(‘hi’);
}
We still have some limitations like giving a parameter to the middleware or adding multiple middlewares to the route.
That’s all.