Skip to content

feat(router): Add fallback property for unmatched routes - #196

Merged
nielsenko merged 10 commits into
serverpod:mainfrom
nielsenko:router-fallback
Oct 14, 2025
Merged

nielsenko merged 10 commits into
serverpod:mainfrom
nielsenko:router-fallback

Conversation

@nielsenko

@nielsenko nielsenko commented Oct 7, 2025 •

Copy link
Copy Markdown
Collaborator

Description

  • Added Router.fallback property for handling unmatched routes (default to 404).
  • Added RouterHandler.asHandler extension on Router<Handler> allowing it to be used directly as a Handler.
  • Updated documentation and examples to prefer Router.use() and Router.fallback over Pipeline and Cascade composition
  • Added tests for new functionality
  • Refactored existing tests and examples to demonstrate preferred patterns

This provides a more direct API for common routing scenarios while maintaining backward compatibility with existing middleware patterns.

Related Issues

Fixes: #197

Pre-Launch Checklist

  • This update focuses on a single feature or bug fix.
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

  • No breaking changes.

All changes are additive. Existing Pipeline and Cascade patterns continue to work.

Additional Notes

The Router.fallback property only applies to path misses (404). Method misses (405) still return the appropriate response with Allow header as before.

Summary by CodeRabbit

  • New Features
    • Use the Router directly as a server handler (no separate pipeline required).
    • Router-level fallback for unmatched paths, improving 404/405 behavior.
    • Access pathParameters, matchedPath, and remainingPath from the request context.
    • Router-based middleware support showcased (e.g., logging, authentication).
  • Documentation
    • README and examples updated to the Router-first setup and new context accessors.
  • Tests
    • Test suites updated to validate fallback behavior, method handling, middleware, nested routes, parameters, and wildcard routing.

@coderabbitai

coderabbitai Bot commented Oct 7, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Switches examples/tests from Pipeline-based composition to using Router as a direct handler, adds a nullable Router.fallback, exposes router-as-handler via an extension (asHandler/call), extends RequestContext with matchedPath/pathParameters/remainingPath, and refactors routeWith to return a callable middleware.

Changes

Cohort / File(s) Summary
Docs & examples
README.md, example/example.dart, example/middleware_example.dart, example/multi_isolate.dart
Replace Pipeline-based handler composition with Router usage; start servers with router.asHandler/router.call; add router-level middleware via router.use(...) and set router.fallback for 404; update comments.
Routing middleware
lib/src/middleware/routing_middleware.dart
routeWith<T> now returns a callable middleware (builder.asMiddleware/call); add RequestContextEx getters (matchedPath, pathParameters, remainingPath); add RouterHandler extension exposing Handler get asHandler.
Router core
lib/src/router/router.dart
Add public nullable fallback field on Router<T> with documentation describing fallback behavior and composition semantics.
Examples (auth)
example/middleware_example.dart
Add AuthMiddleware class and extension on RequestContext { User get user => _auth[this]; }; middleware populates request user and examples updated to rely on ctx.user.
Tests — routing middleware / router handler
test/middleware/routing_middleware_test.dart, test/router/router_handler_test.dart
Migrate tests to invoke router.asHandler/router.call; add comprehensive router handler tests (200/404/405, Allow header, params, matched/remaining path, wildcard, nested routes, middleware, fallback semantics).
Tests — static/mounted
test/static/create_file_handler_test.dart, test/static/mounted_test.dart
Replace Pipeline+routeWith test scaffolding with Router<Handler> + router.fallback; obtain handler via router.asHandler and preserve expected responses.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor C as Client
  participant S as Server
  participant R as Router<Handler>
  participant H as MatchedHandler
  participant F as FallbackHandler

  C->>S: HTTP request
  S->>R: router.call(ctx)

  alt path & method match
    R->>R: set matchedPath / pathParameters / remainingPath
    R->>H: invoke(ctx)
    H-->>R: response
    R-->>S: response (e.g., 200)
  else path matched but method not allowed
    R-->>S: 405 Method Not Allowed + Allow header
  else path miss
    alt fallback set
      R->>F: invoke(ctx)
      F-->>R: response (custom or 404)
      R-->>S: response
    else no fallback
      R-->>S: 404 Not Found
    end
  end

  note right of R: RequestContextEx exposes matchedPath, pathParameters, remainingPath
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly describes the main feature addition by naming the router component and the fallback property for unmatched routes, reflecting the primary change in this PR.
Linked Issues Check ✅ Passed The implementation adds the Router.fallback property and RouterHandler.asHandler extension, updates examples and tests to allow setting fallback late, and replaces pipeline compositions without altering routing performance or semantics, fully addressing the objectives from issue #197.
Out of Scope Changes Check ✅ Passed All code changes focus on introducing and supporting the Router.fallback API and Router.asHandler extension, with corresponding example and test updates, and there are no unrelated modifications outside the linked issue’s scope.
Description Check ✅ Passed The PR description follows the repository template by including a detailed Description section explaining what and why, a Related Issues section linking #197, a completed Pre-Launch Checklist, a Breaking Changes declaration, and Additional Notes on behavior, covering all required information.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Oct 7, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.90%. Comparing base (ef24eec) to head (f86dc61).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #196   +/-   ##
=======================================
  Coverage   91.90%   91.90%           
=======================================
  Files          86       86           
  Lines        3248     3248           
  Branches     1666     1666           
=======================================
  Hits         2985     2985           
  Misses        263      263           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 7, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/src/middleware/routing_middleware.dart (1)

71-81: Constructor can throw LateInitializationError; throw ArgumentError instead.

if T is not Handler and toHandler is null, _toHandler remains uninitialized and reading it in ArgumentError.checkNotNull(_toHandler, ...) triggers a LateInitializationError, not a clear ArgumentError. Initialize or explicitly throw.

Apply this diff:

   _RoutingMiddlewareBuilder(
     this._router, {
     final Handler Function(T)? toHandler,
   }) {
     if (toHandler != null) {
       _toHandler = toHandler;
     } else if (_isSubtype<T, Handler>()) {
       _toHandler = (final x) => x as Handler;
-    }
-    ArgumentError.checkNotNull(_toHandler, 'toHandler');
+    } else {
+      throw ArgumentError(
+        'toHandler must be provided when T is not a Handler.',
+      );
+    }
   }
🧹 Nitpick comments (2)
test/router/router_handler_test.dart (1)

18-316: Solid coverage, behavior matches design.

Tests exercise 404/405, fallback, params, wildcards, matched/remaining paths, middleware. Looks good. Consider adding one routeWith-based test to assert PathMiss delegates to next (to lock BC for pipeline usage).

lib/src/middleware/routing_middleware.dart (1)

87-94: Minor duplication: centralize 405 response creation.

The 405 construction is duplicated in routeWith and RouterHandler.call. Extract a small helper to avoid drift.

Example outside-diff addition:

static FutureOr<HandledContext> _respond405(
  RequestContext ctx,
  Iterable<Method> allowed,
) => ctx.respond(
  Response(405, headers: Headers.build((h) => h.allow = allowed)),
);

Then replace both sites with _respond405(ctx, result.allowed).

Also applies to: 187-193

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2910d7a and afbdc04.

📒 Files selected for processing (10)
  • README.md (1 hunks)
  • example/example.dart (1 hunks)
  • example/middleware_example.dart (2 hunks)
  • example/multi_isolate.dart (1 hunks)
  • lib/src/middleware/routing_middleware.dart (4 hunks)
  • lib/src/router/router.dart (1 hunks)
  • test/middleware/routing_middleware_test.dart (3 hunks)
  • test/router/router_handler_test.dart (1 hunks)
  • test/static/create_file_handler_test.dart (2 hunks)
  • test/static/mounted_test.dart (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-22T07:34:15.403Z
Learnt from: CR
PR: serverpod/relic#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-22T07:34:15.403Z
Learning: Applies to {lib,example}/**/*.dart : Implement handlers as functions processing RequestContext and returning ResponseContext; use middleware to wrap handlers and compose via a pipeline

Applied to files:

  • example/multi_isolate.dart
  • example/middleware_example.dart
  • example/example.dart
🔇 Additional comments (10)
lib/src/router/router.dart (1)

47-62: Well-designed fallback mechanism with clear documentation.

The nullable fallback field is properly typed and the documentation clearly explains:

  • When it applies (path miss/404) vs when it doesn't (method miss/405)
  • Composition behavior (only top-most fallback is used)
  • Typical usage pattern via example

This design allows users to explicitly set or unset the fallback, and the distinction between path and method misses is important for proper HTTP semantics.

example/example.dart (1)

8-17: Clear demonstration of the new router-based pattern.

The example effectively showcases:

  • Inline middleware composition via Router.use()
  • Centralized 404 handling via Router.fallback
  • Direct router invocation via router.call

The explanatory comments help users understand the benefits of this approach over Pipeline/Cascade composition.

example/multi_isolate.dart (1)

31-37: LGTM! Consistent adoption of router.call pattern.

The multi-isolate example correctly demonstrates the new router-based serving approach, consistent with other examples in the codebase.

test/middleware/routing_middleware_test.dart (3)

231-233: LGTM! Tests correctly adopt router-level fallback.

The nested routing test now uses mainRouter.fallback for 404 handling and mainRouter.call as the handler, replacing the previous Pipeline-based approach while maintaining the same test assertions and coverage.


274-276: LGTM! Multi-level attachment test updated consistently.

The test correctly demonstrates router.call usage with fallback for deeply nested routing scenarios, ensuring parameters are properly captured across multiple levels.


311-313: LGTM! Repeated parameter test uses new pattern.

The test for repeated parameters across nested routers correctly adopts the router.call pattern with router-level fallback.

example/middleware_example.dart (1)

14-21: LGTM! Middleware example demonstrates path-specific middleware.

The example clearly shows how to apply middleware to specific routes using Router.use('/api', AuthMiddleware().call) and serves via router.call, demonstrating the new pattern for composing middleware.

test/static/mounted_test.dart (1)

24-27: LGTM! Static handler test updated to router.call pattern.

The test correctly adopts the router-level fallback and router.call as the handler, maintaining test coverage while using the new recommended approach.

test/static/create_file_handler_test.dart (1)

27-35: LGTM! File handler tests consistently use router.call pattern.

All test cases have been updated to use Router<Handler> with router-level fallback instead of Pipeline-based composition, maintaining the same test coverage and behavior.

README.md (1)

46-54: LGTM! README updated to showcase the new router pattern.

The example code has been updated to demonstrate the recommended approach using Router<Handler> with inline middleware via use(), centralized 404 handling via fallback, and direct serving via router.call. This provides clear guidance for users adopting the framework.

@nielsenko
nielsenko requested a review from Copilot October 7, 2025 13:26
@nielsenko nielsenko self-assigned this Oct 7, 2025

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds fallback functionality to the Router class and enables Router to be used directly as a Handler. The changes provide a more convenient API for handling unmatched routes (404s) and eliminate the need for Pipeline/Cascade composition in common scenarios.

  • Added Router.fallback property for handling unmatched routes
  • Added RouterHandler.call() extension allowing Router<Handler> to be used directly as a Handler
  • Updated documentation and examples to prefer the new Router-based API over Pipeline composition

Reviewed Changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated no comments.

Show a summary per file
File Description
lib/src/router/router.dart Added fallback property with documentation
lib/src/middleware/routing_middleware.dart Added RouterHandler extension and comprehensive documentation
test/router/router_handler_test.dart Added comprehensive test suite for new router handler functionality
test/static/mounted_test.dart Updated to use router.fallback and router.call
test/static/create_file_handler_test.dart Refactored tests to use new router API
test/middleware/routing_middleware_test.dart Updated tests to use router.fallback and router.call
example/example.dart Updated main example to demonstrate router.use and router.fallback
example/middleware_example.dart Simplified example using router.call
example/multi_isolate.dart Updated to use router-based approach
README.md Updated documentation to show preferred router-based API

@nielsenko
nielsenko marked this pull request as ready for review October 7, 2025 13:45
@nielsenko
nielsenko requested a review from a team October 7, 2025 13:45

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functionality looks great! Glad to see the usage of the package being simplified.

I have a suggestion regarding creating a more self-documenting API. Let me know what you think.

Comment thread example/example.dart Resolved
@nielsenko

nielsenko commented Oct 9, 2025 •

Copy link
Copy Markdown
Collaborator Author

@nielsenko
nielsenko force-pushed the router-fallback branch 5 times, most recently from 95f6a69 to 39547f1 Compare October 10, 2025 10:25
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@nielsenko
nielsenko marked this pull request as draft October 10, 2025 11:08
@nielsenko
nielsenko force-pushed the router-fallback branch 4 times, most recently from fdee670 to 6c2a5b3 Compare October 11, 2025 08:24
@nielsenko
nielsenko marked this pull request as ready for review October 11, 2025 08:32
@nielsenko

Copy link
Copy Markdown
Collaborator Author

This is stacked on top of #209. Please review that first

Adds a fallback property to Router<T> that is called when no route
matches a request path (404, not 405). This provides a simpler
alternative to using Pipeline or Cascade for basic fallback scenarios.

Example usage:
  final router = Router<Handler>()
    ..get('/users', usersHandler)
    ..fallback = notFoundHandler;
…stContextEx

Improves documentation for routing middleware:
- Adds detailed doc comments for routeWith() function
- Documents behavior for path miss (calls next) vs method miss (returns 405)
- Provides examples for Router<Handler> and custom types
- Documents toHandler parameter usage
- Adds comprehensive docs for RequestContextEx extension properties
- Explains matchedPath, pathParameters, and remainingPath with examples
- Notes relationship with RouterHandler.call extension
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! One comment to fix otherwise it looks good, feel free to close when resolved.

@nielsenko
nielsenko merged commit 4d70a72 into serverpod:main Oct 14, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Dec 15, 2025
7 of 8 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Feb 17, 2026
7 of 8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Router.fallback Handler property

3 participants