Skip to content

Middleware

Handle low-level HTTP concerns before they reach your controllers.

Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next() middleware function in the application’s request-response cycle.

NestForge middleware are, by default, equivalent to Axum/Tower middleware. They are the perfect place to handle low-level HTTP concerns.


The easiest way to create a middleware is using the nestforge::middleware! macro.

use nestforge::middleware;
middleware!(LoggerMiddleware, |req, next| {
println!("Incoming Request: {} {}", req.method(), req.uri().path());
// Call the next middleware/handler in the chain
let res = (next)(req).await;
println!("Outgoing Response: {}", res.status());
res
});

In NestForge, you configure middleware within the NestForgeFactory during application bootstrap. You can apply middleware globally or to specific routes.

To apply a middleware to every single route in your application:

src/main.rs
NestForgeFactory::<AppModule>::create()?
.use_middleware::<LoggerMiddleware>()
.listen(3000)
.await?;

You can use the .configure_middleware() builder to apply middleware selectively.

NestForgeFactory::<AppModule>::create()?
.configure_middleware(|consumer| {
// Apply to all routes
consumer.apply::<LoggerMiddleware>().for_all_routes();
// Apply only to /users prefixed routes
consumer.apply::<AuthMiddleware>().for_routes(["/users"]);
// Apply to /admin but exclude the health check
consumer.apply::<AuditMiddleware>()
.exclude(["/admin/health"])
.for_routes(["/admin"]);
consumer
})
.listen(3000)
.await?;

Middleware is best suited for cross-cutting HTTP concerns that don’t require knowledge of the specific route handler being executed.

  • Request Logging: Logging details about every hit.
  • CORS Configuration: Handling Cross-Origin Resource Sharing.
  • Header Manipulation: Adding or removing standard HTTP headers.
  • Compression: Gzip/Brotli encoding of responses.
  • Request ID Tracking: Generating and attaching unique IDs to every request.

NestForge middleware can also benefit from dependency injection. Since they are registered via the factory, they can resolve providers registered in your modules.

pub struct AuthMiddleware {
config: Inject<ConfigService>,
}
middleware!(AuthMiddleware, |req, next| {
// Access self.config here
(next)(req).await
});