Skip to content

🐞 fix (server): support for awaiting next.js 15 params #1805

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 24, 2024

Conversation

AmruthPillai
Copy link
Contributor

@AmruthPillai AmruthPillai commented Oct 24, 2024

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve modifying the Context type definition in packages/server/src/next/app-route-handler.ts. The params property is updated from a synchronous object to a promise that resolves to an object containing a path array. This requires the request handler function to use await when accessing context.params, affecting the logic for checking the path parameter and constructing the path variable.

Changes

File Path Change Summary
packages/server/src/next/app-route-handler.ts Updated Context type to make params a promise that resolves to an object with a path array. Adjusted request handler logic to await context.params.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Handler

    Client->>Server: Request
    Server->>Handler: Process Request
    Handler->>Handler: Await context.params
    Handler->>Handler: Check if path exists
    Handler->>Handler: Construct path variable
    Handler-->>Server: Response
    Server-->>Client: Return Response
Loading

Assessment against linked issues

Objective Addressed Explanation
Update NextRequestHandler to await params before accessing properties (1797)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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: 0

🧹 Outside diff range and nitpick comments (2)
packages/server/src/next/app-route-handler.ts (2)

31-42: Consider enhancing error handling for params resolution.

The async params handling is implemented correctly. However, consider adding explicit error handling for the await context.params operation.

Consider wrapping the params resolution in a try-catch:

-        const params = await context.params;
+        let params;
+        try {
+            params = await context.params;
+        } catch (error) {
+            return NextResponse.json(
+                { message: 'Failed to resolve request parameters' },
+                { status: 500 }
+            );
+        }

Line range hint 13-19: Consider updating function documentation.

The function documentation should mention that context.params is now asynchronous in Next.js 15+. This helps developers understand the potential need for error handling around params resolution.

Consider adding a note in the JSDoc:

 /**
  * Creates a Next.js 13 "app dir" API route request handler which encapsulates Prisma CRUD operations.
  *
+ * @remarks Since Next.js 15, `context.params` is asynchronous and must be awaited.
  * @param options Options for initialization
  * @returns An API route request handler
  */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fac631b and e5ee13d.

📒 Files selected for processing (1)
  • packages/server/src/next/app-route-handler.ts (2 hunks)
🔇 Additional comments (1)
packages/server/src/next/app-route-handler.ts (1)

9-9: LGTM! Note: Breaking change in Context type.

The update to make params asynchronous aligns with Next.js 15's behavior. This is a breaking change that requires consumers to update their code to await params.

Let's check for any direct usage of this type in the codebase:

✅ Verification successful

Let me try a different search strategy to verify the usage of this Context type.


Let me search for any references to this specific file to ensure we catch all potential imports, even if they're importing the type differently.


Let me check how the AppRouteHandler is being used in the importing file to understand the impact.


Based on the verification results, I can now provide the final response:

Breaking change is properly encapsulated and has limited impact

The Context type change is well-contained within the app-route-handler.ts module and is only used internally. The module is exported as a default export and consumed through the NextRequestHandler factory function in index.ts, which properly encapsulates the internal changes. External consumers interact with the module through the documented AppRouteRequestHandlerOptions interface, which is not affected by this change.

  • The type Context is not exported or directly used outside of app-route-handler.ts
  • The only import of this module is in index.ts which uses it as an implementation detail
  • The public API (NextRequestHandler and its options interfaces) remains unchanged
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other files that might be using the Context type
rg -l "Context.*=.*{.*params.*}"

Length of output: 154


Script:

#!/bin/bash
# Search for Context type usage with proper escaping and context
rg -A 2 "type Context"

# Also search for imports of Context type
rg "import.*Context.*from.*app-route-handler"

Length of output: 1007


Script:

#!/bin/bash
# Search for any imports from app-route-handler.ts
rg "from ['\"].*app-route-handler['\"]"

# Search for any usage of the specific params pattern within the codebase
ast-grep --pattern 'const { params } = $_: Context'

Length of output: 199


Script:

#!/bin/bash
# Get the content of the importing file to see how AppRouteHandler is used
cat packages/server/src/next/index.ts

# Also search for any other files that might be using the handler
rg -l "AppRouteHandler"

Length of output: 1914

@AmruthPillai
Copy link
Contributor Author

I refactored the code a little bit to include @coderabbitai's suggestions, they were actually pretty good and didn't expect AI to generate good code reviews.

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

Tip

For best results, initiate chat on the files or code changes.

@AmruthPillai Thank you for incorporating my suggestions! I'm delighted to hear that you found them helpful.

(^・ω・^ )


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (2)
packages/server/src/next/app-route-handler.ts (2)

14-14: Consider enhancing the documentation with a reference link.

While the remark clearly explains the Next.js 15 change, it would be more helpful to include a link to the relevant Next.js documentation for further reference.

- * @remarks Since Next.js 15, `context.params` is asynchronous and must be awaited.
+ * @remarks Since Next.js 15, `context.params` is asynchronous and must be awaited.
+ * @see https://nextjs.org/docs/app/api-reference/file-conventions/route#params-and-searchparams

35-39: Consider adding error logging for better debugging.

While the error handling is correct, logging the actual error would help with debugging in production environments.

 try {
     params = await context.params;
 } catch (error) {
+    options.logger?.error('Failed to resolve request parameters:', error);
     return NextResponse.json({ message: 'Failed to resolve request parameters' }, { status: 500 });
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e5ee13d and 224f65f.

📒 Files selected for processing (1)
  • packages/server/src/next/app-route-handler.ts (2 hunks)
🔇 Additional comments (1)
packages/server/src/next/app-route-handler.ts (1)

9-9: LGTM: Type definition properly handles async params.

The updated Context type correctly accommodates both Promise-based params (Next.js 15+) and synchronous params (older versions), ensuring backward compatibility.

@ymc9
Copy link
Member

ymc9 commented Oct 24, 2024

I refactored the code a little bit to include @coderabbitai's suggestions, they were actually pretty good and didn't expect AI to generate good code reviews.

Yes, it sometimes helps me find important issues. I go through its comments every time 😄. The change looks good to me and I'm merging it. Than you for the contribution!

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

Tip

For best results, initiate chat on the files or code changes.

@ymc9 Thank you for your support! I'm happy to hear that my suggestions were helpful.

(^・ω・^ )

@ymc9 ymc9 merged commit b8c84a5 into zenstackhq:dev Oct 24, 2024
13 checks passed
@AmruthPillai AmruthPillai deleted the fix/support-next-15-await-params branch October 24, 2024 19:25
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