By default, middleware is global. To restrict middleware to specific handlers or blueprints, your middleware struct must inherit from crow::ILocalMiddleware.
Execution Order: Global middleware is run first, followed by the enabled local middleware for the current handler. In both cases, they follow the order specified in the crow::App definition.
To apply local middleware to a route, use .CROW_MIDDLEWARES(app, MiddlewareName). To apply it to a blueprint, use bp.CROW_MIDDLEWARES(app, MW1, MW2).
// 1. Define the local middleware
struct LocalMiddleware : crow::ILocalMiddleware
{
struct context {};
void before_handle(crow::request& req, crow::response& res, context& ctx) {}
void after_handle(crow::request& req, crow::response& res, context& ctx) {}
};
// 2. Apply to a specific route
CROW_ROUTE(app, "/with_middleware")
.CROW_MIDDLEWARES(app, LocalMiddleware)
([]() {
return "Hello world!";
});
// 3. Apply to a blueprint
Blueprint bp("with_middleware");
bp.CROW_MIDDLEWARES(app, FistLocalMiddleware, SecondLocalMiddleware);