Description
Add support for middleware to Serverpod's webserver, Relic, which can be used for custom logging, authentication, data validation, error handling, or other logic. The middleware should be able to modify a request and take over a response. We may potentially want to build a bridge for shelf middleware in a separate package.
Serverpod's middleware can be an abstract class Middleware. It's primary method is handleRequest, which is analog to the handleRequest method in a Route. The difference is that the method in the middleware can return null, in which case control over the response is passed on to the next chained middleware or to the Route.
If the middleware needs to override the Request, it can do so by calling the modifyRequest method.
abstract class Middleware {
Future<Response?> handleRequest(Session session, Request request);
void modifyRequest(Request request) {
...
}
}The middlewares can be injected using a Router or WebServer (see #2489). Either directly to the Router, affecting all routes:
pod.webServer.addMiddleware(MyCustomLogger());Or, when adding the routes:
pod.webServer.addRoute(
MyRoute(),
middleware: [MyMiddleware()],
);
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone 🚀
Activity
SandPod commentedon Jul 22, 2024
Why do we need a separate method for modifyRequest? Is the request passed to the method immutable? If not, what would happen if it is modified in the middleware directly?
vlidholt commentedon Jul 22, 2024
Yes, the thinking is that the
Requestis immutable, but has achangemethod that returns a modifiedRequest. This is howshelfworks.baudee commentedon Apr 19, 2025
This feature will be only for the web server ? Could be nice to have it as well for the Endpoints
vanlooverenkoen commentedon Apr 22, 2025
I agree with @baudee having it in the endpoints would simplify my endpoints code by A LOT!
dkbast commentedon May 2, 2025
This would be super good for setting the CORS headers :)