You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Implement a concise, fluent API style for routing and middleware #71
This fluent interface would simplify the common use case of setting up routes and middleware, while still leveraging the existing routing and middleware implementation underneath.
Benefits
Reduces boilerplate for simple applications
More approachable for beginners
Could provide a smooth transition path to the more advanced concepts
Maintains all the power of the current implementation
Related
This came from discussion in PR #68 which implements the routing middleware.
I wanted to know if you guys already have plans for this improvement
I'm asking because I have implemented a very similar Router to yours that has this type of API, it's inspired by echo and built on top of shelf (for now)
It is currently available in my package, so that I can use it in multiple personal projects, but I've created a branch where I've polished the code and added some tests (so that you guys can have a look at most of the features I've added)
this is a small example of the router:
final router =Router()
//NOTE: adds a middleware globally (or to a Group if called from one)
..use((innerHandler) {
return (request) async {
final res =awaitinnerHandler(request);
return res.change(headers: {"x-powered-by":"test"});
};
})
..get("/hello", (Request req) =>Response.ok("Hello"));
//NOTE: this is a group - they can also be nestedfinal _ = router.group("/api", (innerHandler) {
return (request) async {
final res =awaitinnerHandler(request);
return res.change(headers: {"x-group":"1"});
};
})..get("/ping", (Request req) =>Response.ok("pong"));
final _ = router.group("/g1", (innerHandler) {
return (request) async {
final res =awaitinnerHandler(request);
return res.change(headers: {"x-group":"g1"});
};
})..get("/a", (Request req) =>Response.ok("a"));
I'd love to contribute by helping add these features to the router if you guys think they are a good fit
Thanks for your interest in serverpod and relic. As you noticed we have recently added a new router to relic. This issue is a reminder to improve on the DX.
Some effort has been made. The relic router already has convenience extensions for the common verbs as well as any:
This is close to how echo does it. I'll add this convenience in the next release.
So the remaining work for this issue is how to handle setup of route specific middleware with a nice api (ie. with or use in echo parlor). This is still outstanding work. I'm very open to discussions on how to do this. One hurdle I see is that it conflicts with my efforts to keep the router oblivious to the payload (The relic router is a generic that can route to any T not just a Handler).
I wasn't actually aware of your work until recently (still cannot find the routeez package on pub dev), but I have looked into spanner and routingkit and added some comparative benchmarks of these.
Wrt. your upcoming package routeez this seems to be a complete router in and off itself. I would love to add comparative benchmarks to our harness once released, but we are not currently contemplating replacing what we just landed spring.
However, relic (like shelf) is not a very opinionated, so it works fine with other routers if you would like to make routeez compatible with relic.
I have seen the router added to relic, and my intention was not to change it completely but to present a new API that could be added/adapted to it
In fact, I'm not looking to publish routeez. I do not like the idea of yet another router even if an initial version of it is inside of a package I have already published (htmdart), I am looking forward to remove it completely from it
So based on your comment, I started experimenting with the relic router in order to add these features (mainly the ability to add middlewares directly from the router)
Groups
Router<T>.group cannot use Router<T>.attach
The common use of attach is: We have a different Router with all its routes already created that we need to add to our main Router
final router =Router()..get("/", ...);
final apiRouter =Router()..get("/user/:id", ...);
router.attach("/api", apiRouter);
A Group, however, is used in a subtly different way. It is created directly from the main Router and after its creation, we add routes to it, there is no need to attach our group to our router
final router =Router()..get("/", ...);
final apiGroup = router.group("/api")..get("/user/:id", ...);
Why is this important?
It matters in cases where we would like to share some context in between the Routers that we are creating
In order to make this possible I created a new class called RouteBuilder<T>
RouteBuilder<T>
RouteBuilder<T> is an abstract class that contains the basic initial Router<T> functionality
abstractclassRouteBuilder<T> {
RouteBuilder(this.parent, this._routeProvenanceStorage, this._allRoutes);
//NOTE: used when we would like to access a parent's contextfinalRouteBuilder<T>? parent;
//NOTE: used when we would like to know the RouteBuilder<T> that added an specific route to the PathTriefinalRouteProvenanceStore<T> _routeProvenanceStorage;
finalMap<String, dynamic> context = {};
finalPathTrie<_RouterEntry<T>> _allRoutes;
voidadd(finalMethod method, finalString path, finalT route);
Group<T> group(finalString prefix)
}
Then Router<T> and Group<T> extend this abstract class
By doing so, we made it possible to add sub-routes in a "smart" way
Middlewares
Thanks to the context I added to the RouteBuilder<T> middleware tracking can be added as an extension to RouteBuilder<Handler> in this way we would let the Router<T> and RouteBuilder<T> completely generic (In fact, all the router tests pass without any changes to them)
extensionRouteBuilderMiddlewareExonRouteBuilder<Handler> {
Middleware?get middleware {
... get's middlewares from the parents too } Middleware? get _middleware => (context[_middlewareRouterContextKey] as Middleware?); //NOTE: I tried using `with` but it is not possible because it is a dart keyword void use(final Middleware middleware) ...}
Serving the router
Because we are already adding middleware and sub-routing support directly to the router, it would be ideal to server the Router<Handler> without the need to use any Pipeline or Cascade
So I implemented this extension on Router<Handler>
extensionRouterCallExonRouter<Handler> {
FutureOr<HandledContext> call(finalNewContext ctx) async {
final req = ctx.request;
final url = ctx.request.url;
final match =lookup(req.method.convert(), url.path);
if (match !=null) {
ctx._pathParameters = match.parameters;
final handler = match.value;
final builder =getRouteProvenance(handler);
final middleware = builder.middleware;
if (middleware !=null) {
return builder.middleware!(handler)(ctx);
}
returnhandler(ctx);
} else {
//NOTE: what should we do here?//normally routers of this kind give you the option to add a `notFound` handlerthrowUnimplementedError();
}
}
}
which can then be used as
final router =Router<Handler>()...;
awaitserve(router.call, InternetAddress.anyIPv4, 8080);
I've updated one branch of my fork with these changes
I've also ran the tests and I've seen that only 7 of them are not passing (they are from routing_middleware_test.dart because I had to recreate pathParameters in a new extension to make it work from the call method)
I'd love to open a PR and discuss the implementation further, even though it works and all the router tests are passing (including the ones I've added) I think we can still improve it
PS:
I’ve also run the benchmarks and for the lookup there doesn’t seem to be any change. For the add, there is a small overhead, which I believe is due to the _routeProvenanceStorage.
@namzug16 Happy to hear back. I'll push back a bit, but don't be dissuaded. I'm sure we will end with a good solution.
Wrt. groups, I think you misunderstand how attach works. It is not a destructive operation, you can keep working with both the parent and child router after attaching. They are simply pointing at different root nodes in the same trie after being attached to each other, and operations on one will show in the other, and vice versa.
voidmain() {
final parent =Router<int>();
final child = parent.group('/foo'); // groups defined as the simple extension method from above
child.get('/bar', 42);
parent.get('/foo/doo', 1202);
print(parent.lookup(Method.get, '/foo/bar')?.value); // was added to childprint(child.lookup(Method.get, '/doo')?.value); // was added to parent
}
Wrt. naming. Instead of with we could use withMiddleware, but I'm not opposed to use per se.
Wrt. the performance of add. Most routers will be setup on startup, and lookup is the only real concern. And at these speeds the time spend in the handler will dwarf the route lookup anyway (for most request). That said, we should not leave easy performance gains on the table.
I'll take a look at your branch, when I get a bit of time. I hope you find this feedback helpful. Once again thank you for your interest in relic!
Activity
namzug16 commentedon Aug 9, 2025
Hey @nielsenko!
I wanted to know if you guys already have plans for this improvement
I'm asking because I have implemented a very similar Router to yours that has this type of API, it's inspired by echo and built on top of shelf (for now)
It is currently available in my package, so that I can use it in multiple personal projects, but I've created a branch where I've polished the code and added some tests (so that you guys can have a look at most of the features I've added)
this is a small example of the router:
I'd love to contribute by helping add these features to the router if you guys think they are a good fit
nielsenko commentedon Aug 11, 2025
Hi @namzug16
Thanks for your interest in serverpod and relic. As you noticed we have recently added a new router to relic. This issue is a reminder to improve on the DX.
Some effort has been made. The relic router already has convenience extensions for the common verbs as well as any:
and you can add any subset of verbs for the same route if you so desire.
The relic router doesn't currently support implicit sub-router construction, but since we support attach it is trivial to add like this:
This is close to how echo does it. I'll add this convenience in the next release.
So the remaining work for this issue is how to handle setup of route specific middleware with a nice api (ie.
withorusein echo parlor). This is still outstanding work. I'm very open to discussions on how to do this. One hurdle I see is that it conflicts with my efforts to keep the router oblivious to the payload (The relic router is a generic that can route to anyTnot just aHandler).I wasn't actually aware of your work until recently (still cannot find the routeez package on pub dev), but I have looked into spanner and routingkit and added some comparative benchmarks of these.
Wrt. your upcoming package
routeezthis seems to be a complete router in and off itself. I would love to add comparative benchmarks to our harness once released, but we are not currently contemplating replacing what we just landed spring.However, relic (like shelf) is not a very opinionated, so it works fine with other routers if you would like to make
routeezcompatible with relic.namzug16 commentedon Aug 12, 2025
Hey @nielsenko!
Thank you for looking at the comment
I have seen the router added to relic, and my intention was not to change it completely but to present a new API that could be added/adapted to it
In fact, I'm not looking to publish
routeez. I do not like the idea of yet another router even if an initial version of it is inside of a package I have already published (htmdart), I am looking forward to remove it completely from itSo based on your comment, I started experimenting with the relic router in order to add these features (mainly the ability to add middlewares directly from the router)
Groups
Router<T>.groupcannot useRouter<T>.attachThe common use of
attachis: We have a differentRouterwith all its routes already created that we need to add to our mainRouterA
Group, however, is used in a subtly different way. It is created directly from the mainRouterand after its creation, we add routes to it, there is no need to attach our group to our routerWhy is this important?
It matters in cases where we would like to share some
contextin between theRouters that we are creatingIn order to make this possible I created a new class called
RouteBuilder<T>RouteBuilder<T>RouteBuilder<T>is an abstract class that contains the basic initialRouter<T>functionalityThen
Router<T>andGroup<T>extend this abstract classBy doing so, we made it possible to add sub-routes in a "smart" way
Middlewares
Thanks to the
contextI added to theRouteBuilder<T>middleware tracking can be added as an extension toRouteBuilder<Handler>in this way we would let theRouter<T>andRouteBuilder<T>completely generic (In fact, all the router tests pass without any changes to them)Serving the router
Because we are already adding middleware and sub-routing support directly to the router, it would be ideal to server the
Router<Handler>without the need to use anyPipelineorCascadeSo I implemented this extension on
Router<Handler>which can then be used as
I've updated one branch of my fork with these changes
I've also ran the tests and I've seen that only 7 of them are not passing (they are from
routing_middleware_test.dartbecause I had to recreatepathParametersin a new extension to make it work from thecallmethod)I'd love to open a PR and discuss the implementation further, even though it works and all the router tests are passing (including the ones I've added) I think we can still improve it
PS:
I’ve also run the benchmarks and for the lookup there doesn’t seem to be any change. For the add, there is a small overhead, which I believe is due to the
_routeProvenanceStorage.(my branch - the current main branch)
nielsenko commentedon Aug 13, 2025
@namzug16 Happy to hear back. I'll push back a bit, but don't be dissuaded. I'm sure we will end with a good solution.
Wrt. groups, I think you misunderstand how
attachworks. It is not a destructive operation, you can keep working with both the parent and child router after attaching. They are simply pointing at different root nodes in the same trie after being attached to each other, and operations on one will show in the other, and vice versa.will print
assuming:
Wrt. naming. Instead of
withwe could usewithMiddleware, but I'm not opposed touseper se.Wrt. the performance of
add. Most routers will be setup on startup, andlookupis the only real concern. And at these speeds the time spend in the handler will dwarf the route lookup anyway (for most request). That said, we should not leave easy performance gains on the table.I'll take a look at your branch, when I get a bit of time. I hope you find this feedback helpful. Once again thank you for your interest in relic!