Skip to content

Implement a concise, fluent API style for routing and middleware #71

Closed

Description

@coderabbitai

Background

As discussed in PR #68, the current API for setting up routing and middleware is functional but requires learning several concepts upfront.

Proposal

Implement a more concise, Node-style API that would make the framework more approachable for beginners. For example:

const app = server()
   .get('/user/:name/age/:age', hello)
   .any('/', (_) => 'Not found')
   .with(logRequests);

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.

Activity

  1. namzug16 commented on Aug 9, 2025

    @namzug16
    Contributor

    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:

      final router = Router()
        //NOTE: adds a middleware globally (or to a Group if called from one)
        ..use((innerHandler) {
          return (request) async {
            final res = await innerHandler(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 nested
      final _ = router.group("/api", (innerHandler) {
        return (request) async {
          final res = await innerHandler(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 = await innerHandler(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

  2. nielsenko commented on Aug 11, 2025

    @nielsenko
    Collaborator

    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:

    extension RouteEx<T> on Router<T> {
      void get(final String path, final T value) => add(Method.get, path, value);
      void head(final String path, final T value) => add(Method.head, path, value);
      void post(final String path, final T value) => add(Method.post, path, value);
      void put(final String path, final T value) => add(Method.put, path, value);
      void delete(final String path, final T value) => add(Method.delete, path, value);
      void patch(final String path, final T value) => add(Method.patch, path, value);
      void options(final String path, final T value) => add(Method.options, path, value);
      void trace(final String path, final T value) => add(Method.trace, path, value);
      void connect(final String path, final T value) => add(Method.connect, path, value);
    
      void any(final String path, final T value) {
        for (final method in Method.values) {
          add(method, path, value);
        }
      }
    }

    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:

    extension on Router<T> {
      Router<T> group(final String path) {
        final subRouter = Router<T>();
        attach(path, subRouter);
        return subRouter;
      }
    }

    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.

  3. namzug16 commented on Aug 12, 2025

    @namzug16
    Contributor

    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 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

    abstract class RouteBuilder<T> {
      RouteBuilder(this.parent, this._routeProvenanceStorage, this._allRoutes);
    
      //NOTE: used when we would like to access a parent's context
      final RouteBuilder<T>? parent;
    
      //NOTE: used when we would like to know the RouteBuilder<T> that added an specific route to the PathTrie
      final RouteProvenanceStore<T> _routeProvenanceStorage;
    
      final Map<String, dynamic> context = {};
    
      final PathTrie<_RouterEntry<T>> _allRoutes;
    
      void add(final Method method, final String path, final T route);
    
      Group<T> group(final String 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)

    extension RouteBuilderMiddlewareEx on RouteBuilder<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>

    extension RouterCallEx on Router<Handler> {
      FutureOr<HandledContext> call(final NewContext 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);
          }
          return handler(ctx);
        } else {
          //NOTE: what should we do here?
          //normally routers of this kind give you the option to add a `notFound` handler
          throw UnimplementedError();
        }
      }
    }
    

    which can then be used as

    final router = Router<Handler>()...;
    
    await serve(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.

    (my branch - the current main branch)

    Image
  4. nielsenko commented on Aug 13, 2025

    @nielsenko
    Collaborator

    @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.

    void main() {
      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 child
      print(child.lookup(Method.get, '/doo')?.value); // was added to parent
    }

    will print

    42
    1202
    

    assuming:

    extension on Router<T> {
      Router<T> group(final String path) {
        final subRouter = Router<T>();
        attach(path, subRouter);
        return subRouter;
      }
    }

    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!

  5. moved this from Inbox 📫 to Backlog 🗂️ in Serverpod Frameworkson Aug 14, 2025
  6. moved this from Backlog 🗂️ to Planned 🔭 in Serverpod Frameworkson Aug 28, 2025
  7. moved this from Planned 🔭 to Done 🚀 in Serverpod Frameworkson Oct 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions