Middleware

A middleware lets you observe or mutate every request and response that flows through the app — auth, logging, CORS and sessions are typical use cases.

What is middleware

Each middleware is a struct with three things: a per-request context, a before_handle() hook called before the route runs, and an after_handle() hook called after.

Writing a middleware

struct Timer
{
    struct context {
        std::chrono::steady_clock::time_point start;
    };

    void before_handle(crow::request &, crow::response &, context &ctx) {
        ctx.start = std::chrono::steady_clock::now();
    }

    void after_handle(crow::request &, crow::response &res, context &ctx) {
        auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::steady_clock::now() - ctx.start).count();
        res.set_header("X-Render-Time", std::to_string(ms) + "ms");
    }
};

Using middleware

Attach middlewares as template arguments to crow::App:

crow::App<Timer> app;

Inside a handler, retrieve your context with app.get_context<Timer>(req).