Middleware and Authentication
Add cross-cutting logic and protect routes.
What Is Middleware?
Middleware sits between the incoming request and your route handler, able to inspect or modify both the request and the response. It is perfect for logging, CORS, error handling, and authentication.
import VaporThe Middleware Protocol
A custom middleware conforms to AsyncMiddleware and implements respond(to:chainingTo:). You do work, then call next.respond(to:) to continue the chain.
struct LogMiddleware: AsyncMiddleware {
func respond(to req: Request, chainingTo next: AsyncResponder) async throws -> Response {
req.logger.info("Incoming: " + req.url.path)
return try await next.respond(to: req)
}
}All lessons in this course
- Routing and Request Handling
- Content and JSON Encoding
- Fluent ORM and Models
- Middleware and Authentication