Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Oct 24, 2025

Summary by CodeRabbit

  • New Features

    • Added Next.js adapter support for both App Router and Pages Router.
  • Chores

    • Reorganized server adapter layout and build entrypoints.
    • Updated package manifest to include express and next (marked optional).
  • Tests

    • Added and expanded adapter integration tests covering RPC/CRUD and access-policy scenarios.

Copilot AI review requested due to automatic review settings October 24, 2025 23:53
@coderabbitai
Copy link

coderabbitai bot commented Oct 24, 2025

Caution

Review failed

The pull request is closed.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Reorganizes server adapters: moves Express adapter into src/adapter/express, adds a new Next.js adapter supporting both App and Pages routers with type-safe options and overloads, adds route handler factories for app/pages, updates build entries and package deps, and introduces tests for Next adapter and updated Express test import paths.

Changes

Cohort / File(s) Summary
Project config
packages/server/package.json, packages/server/tsup.config.ts
Adds express and next to devDependencies; adds next to peerDependencies and marks express/next optional in peerDependenciesMeta. Updates tsup entry points to src/adapter/express/index.ts and adds src/adapter/next/index.ts.
Express adapter
packages/server/src/adapter/express/middleware.ts, packages/server/test/adapter/express.test.ts
Adjusts import path for ApiHandler/types (now ../../types), adds an inline doc comment for apiHandler in MiddlewareOptions, and updates test import to the adapter path.
Next adapter — core index & types
packages/server/src/adapter/next/index.ts
Adds CommonAdapterOptions, PageRouteRequestHandlerOptions, AppRouteRequestHandlerOptions, and overloaded NextRequestHandler that dispatches to app/pages handlers based on useAppDir. Imports and wires AppRouteHandler and PagesRouteHandler.
Next adapter — App Route handler
packages/server/src/adapter/next/app-route-handler.ts
New factory exporting handler for Next App Router: retrieves client from request, resolves route params, validates and constructs path, optionally parses JSON body, delegates to apiHandler.handleRequest, and returns JSON response with proper status and error handling.
Next adapter — Pages Route handler
packages/server/src/adapter/next/pages-route-handler.ts
New factory exporting handler for Next Pages Router: obtains client via getClient(req,res), validates path from req.query.path, delegates to apiHandler.handleRequest, writes status/body to res, and handles errors (400/500).
Next adapter tests
packages/server/test/adapter/next.test.ts
Adds comprehensive tests exercising RPC CRUD, aggregate/groupBy/count/upsert, and access-policy scenarios via test client helpers and Next.js routing emulation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

  • Pay attention to: type overload correctness and narrowing in next/index.ts.
  • Verify request/response handling and status propagation in app-route-handler.ts and pages-route-handler.ts.
  • Review test helpers in next.test.ts for accurate emulation of Next.js runtime and expected assertions.

Possibly related PRs

Poem

🐰 I hopped through code with carrot-fueled cheer,

Split routes for Next and made paths clear,
Express moved tidy into its new lair,
Tests now guard both handlers with care,
A little hop — adapters all set to steer! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat(server): migrate next.js server adapter" directly corresponds to the main feature being introduced: the creation of a new Next.js adapter structure with comprehensive support for both app router and pages router patterns. The title is concise, specific, and clearly conveys the primary change. While the PR also includes reorganization of the express adapter into the new structure and updates to build configuration, these are secondary infrastructure changes that support the main objective of the Next.js adapter migration. The title accurately reflects the most significant new functionality being added.

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f5b1cb and 31ddde5.

📒 Files selected for processing (2)
  • packages/server/src/adapter/next/index.ts (1 hunks)
  • packages/server/test/adapter/next.test.ts (1 hunks)

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.

@claude
Copy link

claude bot commented Oct 24, 2025

Claude finished @ymc9's task —— View job


Pull Request Review

I've completed a comprehensive review of the Next.js server adapter migration. Here's my detailed analysis:

  • Review new Next.js adapter implementation
  • Analyze code quality and architecture patterns
  • Check security considerations
  • Evaluate test coverage
  • Assess performance implications
  • Verify integration with existing codebase

Code Quality & Architecture

Excellent Implementation

  • Clean separation between App Router and Pages Router handlers
  • Consistent API design following Express adapter patterns
  • Proper TypeScript typing with generic schema support
  • Well-structured factory pattern for handler creation

Architecture Highlights:

  • packages/server/src/adapter/next/index.ts:49-63: Smart overload design allows type-safe selection between App Router and Pages Router based on useAppDir flag
  • Both handlers follow consistent patterns with the Express adapter for error handling and client management
  • Proper async/await usage throughout

Security Analysis

Good Security Practices

  • Input validation for required parameters (packages/server/src/adapter/next/app-route-handler.ts:32-39)
  • Proper error handling prevents information leakage
  • Safe JSON parsing with try-catch blocks (packages/server/src/adapter/next/app-route-handler.ts:43-49)

Minor Security Considerations:

  • Error messages in packages/server/src/adapter/next/app-route-handler.ts:61 expose raw error details. Consider sanitizing error messages in production
  • Path parameter validation is basic - ensure API handler performs additional validation

Test Coverage

Comprehensive Testing

  • packages/server/test/adapter/next.test.ts provides excellent coverage:
    • Full CRUD operations testing (lines 46-167)
    • Access policy validation (lines 169-232)
    • Uses proper Next.js API resolver for realistic testing
    • Both positive and negative test cases

Missing Test Areas:

  • No App Router specific tests (only Pages Router covered)
  • Error scenarios could be more comprehensive
  • Consider adding tests for malformed requests

Performance Considerations

Efficient Implementation

  • Minimal overhead compared to Express adapter
  • Proper async handling prevents blocking
  • Query parameter parsing optimized for Next.js environment

Performance Notes:

  • packages/server/src/adapter/next/app-route-handler.ts:27: Async params resolution is handled properly
  • JSON parsing is only attempted when request body exists
  • No unnecessary object creation or memory allocations

Integration & Consistency

Well Integrated

  • packages/server/package.json:71,75: Proper peer dependency setup for Next.js 15+
  • packages/server/tsup.config.ts:7: Build configuration properly includes Next.js entry point
  • Export structure missing from package.json - see issue below

Issues Found

Critical Issue ⚠️

  • Missing package.json exports: The Next.js adapter is built (tsup.config.ts:7) but not exported in package.json. Users won't be able to import it.

Suggested Fix:
Add to packages/server/package.json exports section:

"./next": {
  "import": {
    "types": "./dist/next.d.ts",
    "default": "./dist/next.js"
  },
  "require": {
    "types": "./dist/next.d.cts", 
    "default": "./dist/next.cjs"
  }
}

Minor Issues:

  1. Error message inconsistency: packages/server/src/adapter/next/pages-route-handler.ts:37 uses .send() instead of .json() for error responses
  2. Comment typo: packages/server/src/adapter/next/index.ts:36 mentions "Prisma instance" instead of "ZenStackClient"

Recommendations

  1. Add package.json export (blocking issue)
  2. Add App Router tests to match Pages Router coverage
  3. Consider error message sanitization for production environments
  4. Fix comment and error response consistency

Overall, this is a high-quality implementation that follows ZenStack patterns well. The critical export issue needs to be addressed before merge.

Copy link
Contributor

Copilot AI left a comment

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 migrates the Next.js server adapter into a new unified adapter structure alongside the Express adapter. The changes reorganize the codebase to support multiple framework adapters under a common adapter/ directory pattern.

Key changes:

  • Restructured adapter organization with Express and Next.js adapters under src/adapter/
  • Added comprehensive test coverage for the Next.js adapter supporting both Pages Router and App Router
  • Updated build configuration and dependencies to include Next.js as an optional peer dependency

Reviewed Changes

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

Show a summary per file
File Description
packages/server/tsup.config.ts Updated build entry points to reflect new adapter directory structure
packages/server/test/adapter/next.test.ts Added comprehensive test suite for Next.js adapter with RPC handler tests
packages/server/test/adapter/express.test.ts Updated import path to reference new adapter directory structure
packages/server/src/adapter/next/pages-route-handler.ts Implemented Pages Router request handler for Next.js API routes
packages/server/src/adapter/next/index.ts Created main entry point with type definitions and factory function for Next.js adapters
packages/server/src/adapter/next/app-route-handler.ts Implemented App Router request handler for Next.js 13+ route handlers
packages/server/src/adapter/express/middleware.ts Updated import path and added missing JSDoc comment for apiHandler option
packages/server/package.json Added Next.js as optional peer dependency and dev dependency
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
packages/server/package.json (1)

27-51: Missing export entry for the Next.js adapter.

The build configuration (tsup.config.ts) generates a next entry, but package.json doesn't expose it in the exports field. Users won't be able to import the Next.js adapter.

Add the Next.js export entry:

         "./express": {
             "import": {
                 "types": "./dist/express.d.ts",
                 "default": "./dist/express.js"
             },
             "require": {
                 "types": "./dist/express.d.cts",
                 "default": "./dist/express.cjs"
             }
+        },
+        "./next": {
+            "import": {
+                "types": "./dist/next.d.ts",
+                "default": "./dist/next.js"
+            },
+            "require": {
+                "types": "./dist/next.d.cts",
+                "default": "./dist/next.cjs"
+            }
         }
🧹 Nitpick comments (3)
packages/server/src/adapter/next/pages-route-handler.ts (2)

29-29: Handle potentially undefined request method.

While Next.js typically populates req.method, the non-null assertion operator could mask edge cases. Consider explicit handling or validation.

Apply this diff to handle undefined method:

-            const r = await options.apiHandler.handleRequest({
-                method: req.method!,
+            if (!req.method) {
+                res.status(400).json({ message: 'missing request method' });
+                return;
+            }
+            const r = await options.apiHandler.handleRequest({
+                method: req.method,

35-35: Use consistent response method.

Error responses use .json() (lines 17, 22, 37), but the success response uses .send(). While both work, consistency improves maintainability.

Apply this diff:

-            res.status(r.status).send(r.body);
+            res.status(r.status).json(r.body);
packages/server/src/adapter/next/app-route-handler.ts (1)

53-53: Handle potentially undefined request method.

While Next.js typically populates req.method, the non-null assertion operator could mask edge cases. Consider explicit handling or validation.

Apply this diff:

+        if (!req.method) {
+            return NextResponse.json({ message: 'missing request method' }, { status: 400 });
+        }
+
         try {
             const r = await options.apiHandler.handleRequest({
-                method: req.method!,
+                method: req.method,
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cccd344 and 1f5b1cb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • packages/server/package.json (1 hunks)
  • packages/server/src/adapter/express/middleware.ts (1 hunks)
  • packages/server/src/adapter/next/app-route-handler.ts (1 hunks)
  • packages/server/src/adapter/next/index.ts (1 hunks)
  • packages/server/src/adapter/next/pages-route-handler.ts (1 hunks)
  • packages/server/test/adapter/express.test.ts (1 hunks)
  • packages/server/test/adapter/next.test.ts (1 hunks)
  • packages/server/tsup.config.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
{packages,samples,tests}/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place packages only under packages/, samples/, or tests/

Files:

  • packages/server/src/adapter/express/middleware.ts
  • packages/server/tsup.config.ts
  • packages/server/test/adapter/express.test.ts
  • packages/server/src/adapter/next/index.ts
  • packages/server/src/adapter/next/pages-route-handler.ts
  • packages/server/package.json
  • packages/server/test/adapter/next.test.ts
  • packages/server/src/adapter/next/app-route-handler.ts
🧬 Code graph analysis (5)
packages/server/src/adapter/express/middleware.ts (1)
packages/sdk/src/schema/schema.ts (1)
  • SchemaDef (10-18)
packages/server/src/adapter/next/index.ts (3)
packages/sdk/src/schema/schema.ts (1)
  • SchemaDef (10-18)
packages/server/src/types.ts (1)
  • ApiHandler (67-77)
packages/orm/src/client/contract.ts (1)
  • ClientContract (50-170)
packages/server/src/adapter/next/pages-route-handler.ts (3)
packages/server/src/adapter/next/app-route-handler.ts (1)
  • factory (13-64)
packages/sdk/src/schema/schema.ts (1)
  • SchemaDef (10-18)
packages/server/src/adapter/next/index.ts (1)
  • PageRouteRequestHandlerOptions (19-29)
packages/server/test/adapter/next.test.ts (3)
packages/server/src/adapter/next/index.ts (2)
  • PageRouteRequestHandlerOptions (19-29)
  • NextRequestHandler (55-63)
packages/sdk/src/schema/schema.ts (1)
  • SchemaDef (10-18)
packages/testtools/src/client.ts (2)
  • createTestClient (52-169)
  • createPolicyTestClient (179-190)
packages/server/src/adapter/next/app-route-handler.ts (3)
packages/server/src/adapter/next/pages-route-handler.ts (1)
  • factory (11-40)
packages/sdk/src/schema/schema.ts (1)
  • SchemaDef (10-18)
packages/server/src/adapter/next/index.ts (1)
  • AppRouteRequestHandlerOptions (34-44)
🔇 Additional comments (8)
packages/server/tsup.config.ts (1)

6-7: LGTM!

The build configuration correctly reflects the new adapter structure with both Express and Next.js entries.

packages/server/src/adapter/express/middleware.ts (2)

4-4: LGTM!

The import path correctly reflects the new adapter directory structure.


10-12: LGTM!

The added documentation improves API clarity.

packages/server/test/adapter/express.test.ts (1)

6-6: LGTM!

The import path correctly reflects the new adapter directory structure.

packages/server/test/adapter/next.test.ts (1)

10-43: LGTM!

The test helper correctly simulates Next.js API routing and integrates with the apiResolver for end-to-end-style testing.

packages/server/src/adapter/next/index.ts (3)

9-14: LGTM!

The common options interface provides clean abstraction for shared adapter configuration.


19-29: LGTM!

The Pages Router options correctly extend common options with page-specific getClient signature.


49-63: LGTM!

The overloaded function signatures provide excellent type safety, distinguishing between Pages Router and App Router based on the useAppDir flag.

@ymc9 ymc9 merged commit 62d731d into dev Oct 24, 2025
4 of 5 checks passed
@claude
Copy link

claude bot commented Oct 24, 2025

Claude finished @ymc9's task —— View job


Pull Request Review

I've completed a comprehensive review of the Next.js server adapter migration. Here's my detailed analysis:

Todo List:

  • Review new Next.js adapter implementation
  • Analyze code quality and architecture patterns
  • Check security considerations
  • Evaluate test coverage
  • Assess performance implications
  • Verify integration with existing codebase

Code Quality & Architecture

Excellent Implementation

  • Clean separation between App Router and Pages Router handlers
  • Consistent API design following Express adapter patterns
  • Proper TypeScript typing with generic schema support
  • Well-structured factory pattern for handler creation

Architecture Highlights:

  • packages/server/src/adapter/next/index.ts:49-63: Smart overload design allows type-safe selection between App Router and Pages Router based on useAppDir flag
  • Both handlers follow consistent patterns with the Express adapter for error handling and client management
  • Proper async/await usage throughout

Security Analysis

Good Security Practices

  • Input validation for required parameters (packages/server/src/adapter/next/app-route-handler.ts:32-39)
  • Proper error handling prevents information leakage
  • Safe JSON parsing with try-catch blocks (packages/server/src/adapter/next/app-route-handler.ts:43-49)

Minor Security Considerations:

  • Error messages in packages/server/src/adapter/next/app-route-handler.ts:61 expose raw error details. Consider sanitizing error messages in production
  • Path parameter validation is basic - ensure API handler performs additional validation

Test Coverage

Comprehensive Testing

  • packages/server/test/adapter/next.test.ts provides excellent coverage:
    • Full CRUD operations testing (lines 46-167)
    • Access policy validation (lines 169-232)
    • Uses proper Next.js API resolver for realistic testing
    • Both positive and negative test cases

Missing Test Areas:

  • No App Router specific tests (only Pages Router covered)
  • Error scenarios could be more comprehensive
  • Consider adding tests for malformed requests

Performance Considerations

Efficient Implementation

  • Minimal overhead compared to Express adapter
  • Proper async handling prevents blocking
  • Query parameter parsing optimized for Next.js environment

Performance Notes:

  • packages/server/src/adapter/next/app-route-handler.ts:27: Async params resolution is handled properly
  • JSON parsing is only attempted when request body exists
  • No unnecessary object creation or memory allocations

Integration & Consistency

Well Integrated

  • packages/server/package.json:71,75: Proper peer dependency setup for Next.js 15+
  • packages/server/tsup.config.ts:7: Build configuration properly includes Next.js entry point
  • Export structure missing from package.json - see issue below

Issues Found

Critical Issue ⚠️

  • Missing package.json exports: The Next.js adapter is built (tsup.config.ts:7) but not exported in package.json. Users won't be able to import it.

Suggested Fix:
Add to packages/server/package.json exports section:

"./next": {
  "import": {
    "types": "./dist/next.d.ts",
    "default": "./dist/next.js"
  },
  "require": {
    "types": "./dist/next.d.cts", 
    "default": "./dist/next.cjs"
  }
}

Minor Issues:

  1. Error message inconsistency: packages/server/src/adapter/next/pages-route-handler.ts:37 uses .send() instead of .json() for error responses
  2. Comment typo: packages/server/src/adapter/next/index.ts:36 mentions "Prisma instance" instead of "ZenStackClient"

Recommendations

  1. Add package.json export (blocking issue)
  2. Add App Router tests to match Pages Router coverage
  3. Consider error message sanitization for production environments
  4. Fix comment and error response consistency

Overall, this is a high-quality implementation that follows ZenStack patterns well. The critical export issue needs to be addressed before merge.


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.

2 participants