Skip to content
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

♻️ Migrate webhook to app router #1442

Merged
merged 3 commits into from
Nov 23, 2024
Merged

♻️ Migrate webhook to app router #1442

merged 3 commits into from
Nov 23, 2024

Conversation

lukevella
Copy link
Owner

@lukevella lukevella commented Nov 23, 2024

Summary by CodeRabbit

  • New Features

    • Modernized webhook handling for Stripe events, improving error management and response structure.
    • Enhanced integration with Sentry for better error capturing.
  • Bug Fixes

    • Improved handling of invalid signatures and unhandled event types in responses.
  • Documentation

    • Updated function signatures to reflect new API handling practices.

Copy link

vercel bot commented Nov 23, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 23, 2024 0:21am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
landing ⬜️ Skipped (Inspect) Nov 23, 2024 0:21am

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

The pull request introduces substantial modifications to the Stripe webhook handling in the route.ts file. Key updates include the transition from NextApiRequest and NextApiResponse to NextRequest and NextResponse, along with the removal of the previous body parser configuration. The webhook validation logic has been restructured, integrating it directly into the new POST function. Error handling has been enhanced, and the response structure has been modernized to align with current Next.js practices.

Changes

File Path Change Summary
apps/web/src/app/api/stripe/webhook/route.ts - Updated import statements to include waitUntil and switch to @sentry/nextjs.
- Changed function signature from stripeApiHandler to POST.
- Removed previous body parser configuration.
- Integrated validatedWebhook logic into POST function.
- Enhanced error handling and response management using NextResponse.json().

Possibly related PRs

🐰 In the code, we hop and play,
Modernizing webhooks day by day.
With Sentry's watch and responses bright,
Our Stripe events now feel just right!
So let’s cheer for changes, big and small,
For a smoother ride, we’ll stand tall! 🌟

Warning

Rate limit exceeded

@lukevella has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 47 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 43a15f5 and f5a2451.


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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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: 1

🧹 Outside diff range and nitpick comments (1)
apps/web/src/app/api/stripe/webhook/route.ts (1)

Line range hint 47-58: Add error handling for metadata parsing in checkout.session.completed

The code directly parses checkoutSession.metadata using checkoutMetadataSchema.parse(checkoutSession.metadata); without handling potential validation errors. If the metadata does not conform to the schema or is missing, parse will throw an exception, causing the function to fail unexpectedly.

Consider using safeParse and handling the result, or wrap the parsing in a try-catch block to manage validation errors gracefully.

Apply this diff to add error handling:

+try {
+  const { userId } = checkoutMetadataSchema.parse(checkoutSession.metadata);
+  if (!userId) {
+    return NextResponse.json(
+      { error: "Missing user ID in metadata" },
+      { status: 400 },
+    );
+  }
+} catch (err) {
+  Sentry.captureException(err);
+  return NextResponse.json(
+    { error: "Invalid metadata format" },
+    { status: 400 },
+  );
+}
-
-const { userId } = checkoutMetadataSchema.parse(checkoutSession.metadata);
-
-if (!userId) {
-  return NextResponse.json(
-    { error: "Missing client reference ID" },
-    { status: 400 },
-  );
-}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 16aca9c and 583659e.

📒 Files selected for processing (1)
  • apps/web/src/app/api/stripe/webhook/route.ts (4 hunks)

apps/web/src/app/api/stripe/webhook/route.ts Show resolved Hide resolved
@vercel vercel bot temporarily deployed to Preview – landing November 23, 2024 12:13 Inactive
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: 2

🧹 Outside diff range and nitpick comments (3)
apps/web/src/app/api/stripe/webhook/route.ts (3)

19-21: Add type safety and validation to timestamp conversion

The helper function could be more robust with proper typing and validation.

Consider this improvement:

-function toDate(date: number) {
+function toDate(timestamp: number): Date {
+  if (timestamp < 0) {
+    throw new Error('Invalid timestamp: negative values are not allowed');
+  }
   return new Date(timestamp * 1000);
 }

135-142: Consolidate error handling patterns

The error handling pattern is duplicated across different sections. Consider extracting common validation logic.

Create a helper function:

function validateMetadata<T>(
  schema: z.ZodSchema<T>,
  data: unknown,
  errorMessage: string
): T {
  const result = schema.safeParse(data);
  if (!result.success) {
    throw new Error(errorMessage);
  }
  return result.data;
}

169-171: Ensure proper cleanup with waitUntil

The PostHog shutdown is correctly deferred using waitUntil, but there might be other cleanup tasks to consider.

Consider creating a comprehensive cleanup function:

+async function cleanup() {
+  return Promise.all([
+    posthog?.shutdown(),
+    // Add other cleanup tasks here
+  ]);
+}

-  waitUntil(Promise.all([posthog?.shutdown()]));
+  waitUntil(cleanup());
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 583659e and 43a15f5.

📒 Files selected for processing (1)
  • apps/web/src/app/api/stripe/webhook/route.ts (7 hunks)
🔇 Additional comments (1)
apps/web/src/app/api/stripe/webhook/route.ts (1)

Line range hint 48-166: Verify webhook event coverage

Let's ensure we're handling all necessary Stripe webhook events for subscription management.

✅ Verification successful

Let me try a different search strategy to find Stripe webhook event handling patterns.


Based on the search results, I can now generate the final response since we have found the key webhook event handlers in the codebase.

Stripe webhook handler implementation is complete and well-structured

The current implementation handles all essential subscription-related webhook events:

  • checkout.session.completed for initial subscription creation
  • customer.subscription.created, customer.subscription.updated, and customer.subscription.deleted for subscription lifecycle management

These events cover the complete subscription management flow from initial checkout to subscription updates and cancellations. Each case includes proper error handling, database updates, and analytics tracking.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other Stripe webhook handlers in the codebase to ensure consistent coverage

# Look for Stripe event handling patterns
rg -t typescript "case \".*?\".*?stripe" --multiline

# Look for subscription-related constants or types
ast-grep --pattern 'type StripeWebhookEvents = $$$'

Length of output: 4396


Script:

#!/bin/bash
# Search for Stripe webhook event handlers with better pattern matching
rg -t ts "case.*checkout\.session|case.*customer\.subscription" -A 2

# Look for Stripe event type definitions or constants
rg -t ts "type.*Stripe.*Event"

# Search for any Stripe-related webhook documentation or configuration
fd README.md | xargs rg -i "stripe.*webhook"

Length of output: 823

apps/web/src/app/api/stripe/webhook/route.ts Show resolved Hide resolved
apps/web/src/app/api/stripe/webhook/route.ts Show resolved Hide resolved
@vercel vercel bot temporarily deployed to Preview – landing November 23, 2024 12:16 Inactive
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 (1)
apps/web/src/app/api/stripe/webhook/route.ts (1)

Line range hint 67-80: Consider using a transaction for user update

The user update operation should be wrapped in a transaction to ensure data consistency in case of failures.

-      await prisma.user.update({
+      await prisma.$transaction(async (tx) => {
+        await tx.user.update({
           where: {
             id: userId,
           },
           data: {
             customerId: checkoutSession.customer as string,
             subscriptionId: checkoutSession.subscription as string,
           },
-        });
+        });
+      });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 43a15f5 and f5a2451.

📒 Files selected for processing (1)
  • apps/web/src/app/api/stripe/webhook/route.ts (7 hunks)
🔇 Additional comments (6)
apps/web/src/app/api/stripe/webhook/route.ts (6)

19-21: LGTM: Helper function is well-defined

The toDate helper function correctly handles Unix timestamp conversion to JavaScript Date objects.


23-46: Remove non-null assertion from signature validation

The ! operator on stripe-signature header is unsafe. A missing signature should be handled explicitly.

The previous review comment about improving webhook validation robustness is still valid. Please refer to the suggested changes in that comment.


137-144: LGTM: Proper schema validation and error handling

The metadata validation using zod is well implemented with appropriate error handling.


171-171: LGTM: Proper cleanup handling

The use of waitUntil ensures that PostHog shutdown is properly handled before the response is sent.


165-168: Return 200 for unhandled event types

The previous review comment about returning 200 status code for unhandled events is still valid. This will prevent unnecessary webhook retries from Stripe.


103-105: Verify business logic for past_due status

Please confirm if treating 'past_due' subscriptions as active aligns with the business requirements. This could affect billing and access control.

✅ Verification successful

Treating 'past_due' status as active is consistent with schema design

The verification shows that 'past_due' is a valid subscription status defined in the database schema's SubscriptionStatus enum, alongside 'active' and 'trialing'. The implementation in the webhook handler aligns with the database design, suggesting this is an intentional business decision to treat past_due subscriptions as active, likely to provide a grace period for payment issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any access control logic that might be affected by this change
rg -l 'subscription.*status.*active' | xargs rg 'past_due'

Length of output: 325


Script:

#!/bin/bash
# Search for subscription status handling patterns across the codebase
rg -A 5 'subscription.*status' --type ts

Length of output: 689


Script:

#!/bin/bash
# Let's check the Stripe webhook handler implementation and any related subscription status checks
ast-grep --pattern 'async function $_(req: Request) {
  $$$
  subscription.status $$$
  $$$
}'

Length of output: 96


Script:

#!/bin/bash
# Let's check the database schema and any type definitions for subscription status
cat packages/database/prisma/schema.prisma

Length of output: 7760

@lukevella lukevella merged commit b161ea0 into main Nov 23, 2024
9 checks passed
@lukevella lukevella deleted the stripe-webhook branch November 23, 2024 12:56
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.

1 participant