Skip to content

feat: Support WebServer.addMiddleware (based on Router.use) - #4035

Merged
nielsenko merged 8 commits into
serverpod:mainfrom
nielsenko:webserver-add-middleware
Oct 7, 2025
Merged

nielsenko merged 8 commits into
serverpod:mainfrom
nielsenko:webserver-add-middleware

Conversation

@nielsenko

@nielsenko nielsenko commented Oct 6, 2025 •

Copy link
Copy Markdown
Collaborator

Description

  • Adds WebServer.addMiddleware method for custom middleware registration.
  • Refactors WebServer to use middleware-based session and exception handling instead of wrapping individual routes.
  • Replaces ServerpodRouter extension type with direct Router<Handler> usage.
  • Sessions are now injected via middleware and accessed through ContextProperty.
  • Add integration test (/example) for using WebServer.addMiddleware.

Fixes: #2499
Fixes: #3553

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

Summary by CodeRabbit

  • New Features

    • Middleware support with per-path registration and per-request session availability.
    • Centralized error handling that reports exceptions and returns consistent 500 responses.
  • Refactor

    • Unified and simplified request routing pipeline for more reliable per-route handling.
  • Tests

    • Added integration tests covering authentication middleware and authenticated routes.
  • Chores

    • Updated relic dependency to ^0.7.0 across packages, templates, and tests.

@coderabbitai

coderabbitai Bot commented Oct 6, 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

Replaces previous routing glue with a Router-based pipeline, adds middleware support (session hydration and exception reporting), exposes session via a RequestContext extension, introduces Route.call(NewContext) as the public per-route entrypoint, updates route registration to use route.call, and bumps relic to ^0.7.0 across packages, templates, and tests.

Changes

Cohort / File(s) Summary
Web server routing & middleware refactor
packages/serverpod/lib/src/web_server/web_server.dart
Replaced legacy routing glue with Router<Handler> initialized with private _SessionMiddleware and _ReportExceptionMiddleware; added WebServer.addMiddleware(Middleware, String); changed addRoute to route via route.call; added Route.call(NewContext) public API delegating to handleCall(Session, NewContext); added RequestContext extension exposing session. Removed previous route-to-handler plumbing.
Integration test: middleware
tests/serverpod_test_server/test_integration/web_server/middleware_test.dart
Added integration tests for authenticated routes, new TestRoute requiring authentication, per-request ContextProperty<AuthenticationInfo>, RequestContext.authInfo extension, and _AuthMiddleware verifying auth and populating per-request auth info.
Dependency bumps: packages
packages/serverpod/pubspec.yaml, packages/serverpod_client/pubspec.yaml
Updated relic dependency from ^0.6.0 to ^0.7.0 (dependency in serverpod, dev_dependency in serverpod_client).
Dependency bumps: templates
templates/pubspecs/packages/serverpod/pubspec.yaml, templates/pubspecs/packages/serverpod_client/pubspec.yaml
Updated template pubspecs to use relic: ^0.7.0.
Dependency bumps: tests/templates
tests/serverpod_test_server/pubspec.yaml, templates/pubspecs/tests/serverpod_test_server/pubspec.yaml
Updated test server pubspecs to use relic: ^0.7.0.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant WS as WebServer
  participant R as Router<Handler>
  participant SM as _SessionMiddleware
  participant EM as _ReportExceptionMiddleware
  participant Rt as Route.call
  participant RC as Route.handleCall

  Client->>WS: HTTP Request
  WS->>R: routeWith(_router)
  R->>SM: handle(request, context)
  SM->>SM: Hydrate Session into Context
  SM->>EM: next(request, context)
  EM->>Rt: try { next(request, context) }
  Rt->>RC: handleCall(session, context)
  RC-->>Rt: HandledContext/Response
  Rt-->>EM: Response
  EM-->>R: Response
  R-->>WS: Response
  WS-->>Client: HTTP Response

  rect rgba(255,220,220,0.18)
  note over EM: On exception -> report and return 500
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The title concisely and accurately describes the primary change of adding support for WebServer.addMiddleware and references the underlying Router.use mechanism without extraneous detail.
Linked Issues Check ✅ Passed The changes introduce a WebServer.addMiddleware API for global and path-specific middleware, refactor session and error handling into a middleware pipeline, and include tests for custom authentication middleware, fully addressing the objectives of issues #2499 and #3553.
Out of Scope Changes Check ✅ Passed All modifications, including dependency version updates and integration tests, directly support the new middleware framework and no unrelated or extraneous changes are present in this pull request.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Description Check ✅ Passed The provided description includes a clear Description section outlining the changes, lists the fixed issues as required, and contains the Pre-launch Checklist with all items marked complete, fully aligning with the template’s core requirements; the only missing element is the optional Breaking changes section.

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.

@nielsenko
nielsenko force-pushed the webserver-add-middleware branch from 50d0d7d to 76ee54f Compare October 6, 2025 07:24
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 6, 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)
packages/serverpod/lib/src/web_server/web_server.dart (1)

96-101: Fix error message: use configured port, not port getter.

On bind failure, port is null; log should reference _config.port.

Apply:

-      await _reportException(e, stackTrace,
-          message: 'Failed to bind socket, '
-              'port $port may already be in use.');
+      await _reportException(
+        e,
+        stackTrace,
+        message: 'Failed to bind socket, port ${_config.port} may already be in use.',
+      );
🧹 Nitpick comments (2)
packages/serverpod/lib/src/web_server/web_server.dart (2)

182-204: Harden exception middleware: guard access to ctx.session.

If session init ever fails, ctx.session can throw during error reporting.

Use a safe fallback:

   Handler call(Handler next) {
     return (ctx) async {
       final request = ctx.request;
       try {
         return await next(ctx);
       } catch (e, stackTrace) {
-        await _webServer._reportException(
+        Session? session;
+        try {
+          session = ctx.session;
+        } catch (_) {
+          session = null;
+        }
+        await _webServer._reportException(
           e,
           stackTrace,
           space: OriginSpace.application,
-          session: ctx.session,
+          session: session,
           request: request,
         );
         return ctx.respond(Response.internalServerError());
       }
     };
   }

62-65: New addMiddleware API mirrors Router.use; consider a global default.

Optional: make path default to '/' for convenience.

-  void addMiddleware(Middleware middleware, String path) =>
+  void addMiddleware(Middleware middleware, [String path = '/']) =>
       _router.use(path, middleware);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c095976 and 76ee54f.

📒 Files selected for processing (7)
  • packages/serverpod/lib/src/web_server/web_server.dart (5 hunks)
  • packages/serverpod/pubspec.yaml (1 hunks)
  • packages/serverpod_client/pubspec.yaml (1 hunks)
  • templates/pubspecs/packages/serverpod/pubspec.yaml (1 hunks)
  • templates/pubspecs/packages/serverpod_client/pubspec.yaml (1 hunks)
  • templates/pubspecs/tests/serverpod_test_server/pubspec.yaml (1 hunks)
  • tests/serverpod_test_server/pubspec.yaml (1 hunks)
🔇 Additional comments (12)
packages/serverpod_client/pubspec.yaml (1)

23-23: Consistent relic upgrade.

Looks good and in sync with templates.

Use the repo-wide check shared in another comment to confirm no ^0.6.x remain.

tests/serverpod_test_server/pubspec.yaml (1)

15-15: LGTM — relic updated to ^0.7.0 here as well.

templates/pubspecs/packages/serverpod/pubspec.yaml (1)

31-31: Template aligned with core package; looks good.

packages/serverpod/lib/src/web_server/web_server.dart (6)

59-61: Route registration via anyOf(..., route.call) looks correct.


81-83: Server pipeline wiring LGTM.

routeWith(_router) + 404 fallback is clear and predictable.


162-180: Session middleware looks good.

Lightweight session hydration before routing; no blocking calls.


206-211: Context property/extension is concise; note it throws if unset.

Given the guard added in the exception middleware, this is fine.

Please ensure all requests pass through _SessionMiddleware (e.g., no alternate entrypoints) so session is always set before route handling.


223-228: Route.call bridge is a clean integration point.

Keeps handleCall(Session, NewContext) intact while aligning with Router.


26-29: Middleware registration order is correct

In relic ^0.7.0 the last-registered middleware runs outermost, so ReportExceptionMiddleware already wraps SessionMiddleware and routes.

templates/pubspecs/packages/serverpod_client/pubspec.yaml (1)

22-22: Relic bump confirmed; all dependencies updated to ^0.7.0 and no ^0.6.x constraints remain.

templates/pubspecs/tests/serverpod_test_server/pubspec.yaml (1)

14-14: Dependency bump verified. All template and generated pubspec.yaml files reference relic ^0.7.0.

packages/serverpod/pubspec.yaml (1)

32-32: Approve relic ^0.7.0 bump; verify all Router, Pipeline, routeWith, ContextProperty, RequestContext, and respondWith usages conform to relic 0.7 APIs.

@nielsenko nielsenko self-assigned this Oct 6, 2025
@nielsenko
nielsenko force-pushed the webserver-add-middleware branch from c011112 to e18177b Compare October 6, 2025 09:56
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 6, 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: 3

🧹 Nitpick comments (3)
packages/serverpod/lib/src/web_server/web_server.dart (2)

209-209: Consider using a named ContextProperty for consistency.

The _sessionProperty is created without a name, while the test file (middleware_test.dart line 85) uses a named property: ContextProperty<AuthenticationInfo>('autoInfo'). This inconsistency may cause confusion about when to use named vs unnamed properties.

Consider providing an explicit name for clarity and to prevent potential key collisions:

-final _sessionProperty = ContextProperty<Session>();
+final _sessionProperty = ContextProperty<Session>('session');

233-233: Address or track the TODO comment.

The TODO questions whether to simplify the API by removing handleCall in favor of just using call. This could be a valuable simplification, but would be a breaking change.

Would you like me to:

  1. Open a new issue to track this API simplification decision?
  2. Evaluate the impact of such a change across the codebase?
tests/serverpod_test_server/test_integration/web_server/middleware_test.dart (1)

65-73: Test description could be clearer about the expected failure.

The test expects a 500 error, but the description doesn't explain why. The 500 occurs because TestRoute always accesses context.authInfo (line 81), which throws on unauthenticated paths where _AuthMiddleware hasn't run. The exception is then caught by _ReportExceptionMiddleware, resulting in a 500 response.

Consider clarifying the test name to indicate the expected exception:

  test(
-      'Given a route that requires authentication is added to an unauthenticated path, '
-      'when a client request the path without authorization, '
-      'then a 500 Internal Error is returned', () async {
+      'Given a route that accesses authInfo is added to a path without auth middleware, '
+      'when a client requests the path, '
+      'then a 500 Internal Server Error is returned due to missing authInfo', () async {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 76ee54f and e18177b.

📒 Files selected for processing (2)
  • packages/serverpod/lib/src/web_server/web_server.dart (6 hunks)
  • tests/serverpod_test_server/test_integration/web_server/middleware_test.dart (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (26)
  • GitHub Check: Serverpod concurrent integration tests (server) (3.35.2)
  • GitHub Check: Serverpod integration tests (server) (3.29.0)
  • GitHub Check: Serverpod integration tests (server) (3.35.2)
  • GitHub Check: Serverpod concurrent integration tests (server) (3.29.0)
  • GitHub Check: Bootstrap tests (3.35.2, ubuntu-latest, tests/bootstrap_project)
  • GitHub Check: Bootstrap tests (3.29.0, ubuntu-latest, tests/bootstrap_project)
  • GitHub Check: CLI e2e tests (3.35.2, ubuntu-latest, tests/serverpod_cli_e2e_test)
  • GitHub Check: CLI e2e tests (3.29.0, ubuntu-latest, tests/serverpod_cli_e2e_test)
  • GitHub Check: Bootstrap tests (3.35.2, windows-latest, tests/bootstrap_project)
  • GitHub Check: Bootstrap tests (3.29.0, windows-latest, tests/bootstrap_project)
  • GitHub Check: Migration e2e tests (3.35.2)
  • GitHub Check: Migration e2e tests (3.29.0)
  • GitHub Check: Serverpod E2E web tests (3.35.2)
  • GitHub Check: Serverpod E2E web tests (3.29.0)
  • GitHub Check: dart analyze downgrade (3.35.2, windows-latest)
  • GitHub Check: Unit tests IO (3.35.2, windows-latest)
  • GitHub Check: dart analyze downgrade (3.35.2, ubuntu-latest)
  • GitHub Check: serverpod generate (3.29.0)
  • GitHub Check: serverpod generate (3.35.2)
  • GitHub Check: Unit tests IO (3.29.0, ubuntu-latest)
  • GitHub Check: Unit tests IO (3.29.0, windows-latest)
  • GitHub Check: Unit tests IO (3.35.2, ubuntu-latest)
  • GitHub Check: dart analyze downgrade (3.29.0, ubuntu-latest)
  • GitHub Check: dart analyze (3.29.0, ubuntu-latest)
  • GitHub Check: dart analyze downgrade (3.29.0, windows-latest)
  • GitHub Check: dart analyze (3.29.0, windows-latest)
🔇 Additional comments (7)
packages/serverpod/lib/src/web_server/web_server.dart (4)

59-60: LGTM! Route registration now uses middleware pipeline.

The change to call route.call instead of direct handling correctly integrates routes into the new middleware-based pipeline.


161-183: LGTM! Session lifecycle is properly managed.

The middleware correctly creates a session per request, stores it in context, and ensures cleanup via the finally block. Resource management is sound.


185-207: LGTM! Exception handling middleware is correctly implemented.

The middleware properly catches exceptions, reports them with session context, and returns an appropriate 500 response.


62-64: Verify external Middleware signature: Definition isn’t found in this repo; confirm in the relic package that Middleware is typedef’d as Handler Function(Handler).

tests/serverpod_test_server/test_integration/web_server/middleware_test.dart (3)

8-24: LGTM! Test setup correctly demonstrates path-specific middleware.

The setup appropriately configures middleware for /api only, creating different behavior for /api/foo (authenticated) vs /bar (unauthenticated). This effectively tests the path-specific middleware functionality.


76-83: LGTM! Test route correctly demonstrates context property access.

The route implementation appropriately accesses context.authInfo to demonstrate how middleware-injected context properties work in practice.


91-100: LGTM! Auth middleware correctly implements the middleware pattern.

The middleware properly:

  1. Checks authentication via ctx.session.authenticated
  2. Returns 401 for unauthenticated requests
  3. Stores AuthenticationInfo in context for downstream handlers
  4. Delegates to the next handler when authenticated

This serves as a good reference implementation for custom middleware.

@nielsenko
nielsenko force-pushed the webserver-add-middleware branch from e18177b to 63f87e3 Compare October 6, 2025 10:11
@nielsenko
nielsenko force-pushed the webserver-add-middleware branch from 63f87e3 to b868507 Compare October 6, 2025 10:15
@nielsenko
nielsenko marked this pull request as ready for review October 6, 2025 10:38
@nielsenko
nielsenko requested a review from a team October 6, 2025 10:41

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

Small suggestion on the test structure

@nielsenko
nielsenko requested a review from exaby73 October 6, 2025 12:47

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

LGTM

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

LGTM!

Just had a couple of NITs.

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

LTGM! 👍

@nielsenko
nielsenko merged commit 105746c into serverpod:main Oct 7, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 7, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Custom middleware Add middleware support to Relic

4 participants