Skip to content

Middleware

How route-targeted middleware works in NestForge and where it fits in the request pipeline.

NestForge supports HTTP middleware through NestForgeFactory::configure_middleware(...) and NestForgeFactory::use_middleware(...).

Middleware is the earliest application-level place to deal with raw HTTP concerns before controller handlers run.

Middleware implements NestMiddleware. The macro form is the fastest way to write one:

use nestforge::middleware;
middleware!(RequestLogger, |req, next| {
{
println!("{} {}", req.method(), req.uri().path());
(next)(req).await
}
});

To run a middleware for every route:

NestForgeFactory::<AppModule>::create()?
.use_middleware::<RequestLogger>();

For more precise control, use a consumer:

NestForgeFactory::<AppModule>::create()?
.configure_middleware(|consumer| {
consumer.apply::<RequestLogger>().for_all_routes();
consumer
.apply::<AdminAuditMiddleware>()
.exclude(["/admin/health"])
.for_routes(["/admin"]);
});

If only certain verbs should trigger middleware, use MiddlewareRoute:

use axum::http::Method;
use nestforge::MiddlewareRoute;
consumer
.apply::<WriteAuditMiddleware>()
.for_routes([MiddlewareRoute::methods("/users", [Method::POST, Method::PUT])]);

Use middleware for concerns such as:

  • request logging
  • header normalization
  • request correlation
  • legacy session or cookie adaptation
  • edge-level request shaping

Do not use middleware for business authorization rules that belong in guards, or for response wrapping logic that belongs in interceptors.