Skip to content

Fix post sign up handling#1078

Merged
elie222 merged 3 commits intomainfrom
fix/post-signup
Dec 9, 2025
Merged

Fix post sign up handling#1078
elie222 merged 3 commits intomainfrom
fix/post-signup

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Dec 9, 2025

Fix post sign up handling by moving side effects to betterAuthConfig.databaseHooks.user.create.after and add /logout page redirecting to /login

Move post-signup side effects into a user.create.after hook and introduce a dedicated postSignUp function; add a /logout client page that logs out then redirects to /login; update the welcome redirect to send null-user sessions to /logout.

📍Where to Start

Start with the betterAuthConfig changes and postSignUp flow in auth.ts. Then review the logout flow in page.tsx and the redirect change in page.tsx.


Macroscope summarized f10d305.

Summary by CodeRabbit

  • New Features

    • Added a dedicated logout page that shows a loading state during sign-out.
  • Bug Fixes

    • Updated session validation to redirect to logout for invalid sessions.
    • Improved sign-up provisioning flow with more robust error handling, logging, and referral/premium-invite processing.
  • Chores

    • Version bumped to v2.21.54.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Dec 9, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Dec 9, 2025 5:49am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 9, 2025

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

Adds a new LogoutPage component that calls logOut on mount and shows a loading state; changes welcome-redirect to send invalid-session users to /logout; replaces sign-in hook with a database user.create.after postSignUp flow that provisions new users; bumps version to v2.21.54.

Changes

Cohort / File(s) Summary
Logout / Redirect
apps/web/app/(landing)/logout/page.tsx, apps/web/app/(landing)/welcome-redirect/page.tsx
Added LogoutPage component that triggers logOut("/login") on mount and renders a loading layout; updated welcome-redirect to point to /logout when a session exists but no user is found.
Auth provisioning hook
apps/web/utils/auth.ts
Replaced events.signIn wiring with a databaseHooks.user.create.after hook that calls new postSignUp({ id, email, name, image }). Refactored sign-up provisioning into structured steps (resolve account provider, create Loops/Resend contacts, track Dub signup) with centralized try/catch, Promise.all for async tasks, and improved logging; renamed/removed prior handleSignIn usage and removed User from imported types.
Metadata
version.txt, package.json
Version bumped v2.21.52 → v2.21.54; package manifest noted in diff.

Sequence Diagram

sequenceDiagram
    participant Client
    participant AuthLayer as Auth Layer / DB Hooks
    participant External as External Services (Loops/Resend/Dub)
    participant DB

    Client->>AuthLayer: Sign Up completes (DB create)
    AuthLayer->>DB: databaseHooks.user.create.after triggers postSignUp
    AuthLayer->>External: Resolve account provider (by userId) and create contacts
    AuthLayer->>External: Track Dub sign-up
    par Parallel async tasks
        AuthLayer->>DB: handlePendingPremiumInvite
        AuthLayer->>DB: handleReferralOnSignUp
    end
    External-->>AuthLayer: Service responses / errors
    DB-->>AuthLayer: Async task results
    AuthLayer-->>Client: Provisioning finished (or errors logged)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Focus review on apps/web/utils/auth.ts (postSignUp flow, Promise.all concurrency, error/capture logging, provider resolution).
  • Verify logout/page.tsx correctly calls logOut and that redirect target behavior in welcome-redirect/page.tsx matches intended UX.
  • Check imports/exports and any type changes after removing User from imports.

Possibly related PRs

Poem

🐰 I hopped in code at break of day,
Pushed users gently on their way,
Loops and Resend lined up in row,
A Dub sign tracked with tidy flow,
Goodbye, login — off we go! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 title 'Fix post sign up handling' directly and accurately summarizes the main change: refactoring post sign-up side effects from the sign-in event handler to an after-hook on user creation.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/post-signup

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.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 4 files

if (!user) redirect("/login");
// Session exists but user doesn't - invalid state, log out
if (!user) redirect("/logout");
if (searchParams.force) redirect("/onboarding");
Copy link
Contributor

Choose a reason for hiding this comment

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

searchParams.force is a string, so if (searchParams.force) treats "false" as truthy and redirects. Consider coercing to a boolean (e.g., compare to "true") before branching.

Suggested change
if (searchParams.force) redirect("/onboarding");
if (searchParams.force === "true") redirect("/onboarding");

🚀 Reply to ask Macroscope to explain or update this suggestion.

👍 Helpful? React to give us feedback.

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

🧹 Nitpick comments (1)
apps/web/utils/auth.ts (1)

163-174: Consider passing provider to postSignUp to avoid extra database query.

The loops() function fetches the account provider separately from the database. Since this information might be available in the calling context (the database hook receives the created user), consider passing the provider as a parameter to postSignUp to eliminate this extra query.

This would require updating the database hook to fetch and pass the account provider:

// In the database hook (lines 116-117)
const account = await prisma.account.findFirst({
  where: { userId: user.id },
  select: { provider: true },
});

await postSignUp({
  id: user.id,
  email: user.email,
  name: user.name,
  image: user.image,
  provider: account?.provider,
}).catch(...)

Then update postSignUp to accept provider as an optional parameter and use it directly instead of fetching it.

📜 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 c64d378 and f10d305.

📒 Files selected for processing (1)
  • apps/web/utils/auth.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use @/ path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type files

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/utils/auth.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: For early access feature flags, create hooks using the naming convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g., inbox-cleaner, pricing-options-2)
Always define types for A/B test variant flags (e.g., type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
Don't export imported variables
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions
Don't use TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/utils/auth.ts
**/{server,api,actions,utils}/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/{server,api,actions,utils}/**/*.ts: Use createScopedLogger from "@/utils/logger" for logging in backend code
Add the createScopedLogger instantiation at the top of the file with an appropriate scope name
Use .with() method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, use createScopedLogger().with() to attach context once and reuse the logger without passing variables repeatedly

Files:

  • apps/web/utils/auth.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/utils/auth.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/utils/auth.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/utils/auth.ts
**/*.{tsx,ts,css}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/utils/auth.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use accessKey attribute on any HTML element
Don't set aria-hidden="true" on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assign tabIndex to non-interactive HTML elements
Don't use positive integers for tabIndex property
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include a title element for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
Assign tabIndex to non-interactive HTML elements with aria-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include a type attribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden)
Always include a lang attribute on the html element
Always include a title attribute for iframe elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...

Files:

  • apps/web/utils/auth.ts
!(pages/_document).{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • apps/web/utils/auth.ts
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/utils/auth.ts
🧠 Learnings (6)
📚 Learning: 2025-11-25T14:37:35.343Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-11-25T14:37:35.343Z
Learning: Applies to apps/web/hooks/use*.ts : Create dedicated hooks for specific data types (e.g., `useAccounts`, `useLabels`) to wrap `useSWR` for individual API endpoints

Applied to files:

  • apps/web/utils/auth.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Use `withAuth` middleware for user-level operations such as user settings, API keys, and referrals that use only `userId`

Applied to files:

  • apps/web/utils/auth.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Always wrap GET API route handlers with `withAuth` or `withEmailAccount` middleware for consistent error handling and authentication in Next.js App Router

Applied to files:

  • apps/web/utils/auth.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account (reading/writing emails, rules, schedules, etc.) - provides `emailAccountId`, `userId`, and `email` in `request.auth`

Applied to files:

  • apps/web/utils/auth.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withAuth` middleware for user-level operations (user settings, API keys, referrals) - provides only `userId` in `request.auth`

Applied to files:

  • apps/web/utils/auth.ts
📚 Learning: 2025-11-25T14:37:30.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-11-25T14:37:30.660Z
Learning: Applies to apps/web/hooks/use*.ts : Create dedicated hooks for specific data types (e.g., `useAccounts`, `useLabels`) that wrap `useSWR`, handle the API endpoint URL, and return data, loading state, error state, and the `mutate` function

Applied to files:

  • apps/web/utils/auth.ts
🧬 Code graph analysis (1)
apps/web/utils/auth.ts (1)
apps/web/utils/error.ts (1)
  • captureException (36-48)
⏰ 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). (2)
  • GitHub Check: test
  • GitHub Check: Review for correctness
🔇 Additional comments (4)
apps/web/utils/auth.ts (4)

6-6: LGTM!

The import cleanup appropriately removes the unused User type, as the database hook now receives the user object directly with the necessary properties.


114-128: Improved architecture for post-signup handling.

The database hook approach is superior to the previous events.signIn pattern because it:

  • Runs specifically after user creation rather than every sign-in
  • Includes proper error handling that prevents signup failures if side effects fail
  • Provides clear logging and exception tracking

The implementation correctly passes the necessary user properties and handles errors gracefully.


211-217: Excellent use of Promise.all for parallel execution.

The parallel execution of post-signup operations (Loops, Resend, Dub, premium invites, and referrals) is well-designed. Each operation has independent error handling, ensuring that a failure in one doesn't block the others.


220-259: Robust implementation with comprehensive error handling.

The updated handlePendingPremiumInvite function demonstrates good practices:

  • Comprehensive try/catch with detailed logging
  • Clear info-level logging for the happy path
  • Proper error context in captureException
  • Safe array filtering that won't fail if email isn't in the list

The implementation correctly handles the premium invite flow without blocking user signup on failures.

Comment on lines +162 to +191
const loops = async () => {
const account = await prisma.account
.findFirst({
where: { userId },
select: { provider: true },
})
.catch((error) => {
logger.error("Error finding account", {
userId,
error,
});

await createLoopsContact(
user.email,
user.name?.split(" ")?.[0],
account?.provider,
).catch((error) => {
const alreadyExists =
error instanceof Error && error.message.includes("409");
if (!alreadyExists) {
logger.error("Error creating Loops contact", {
email: user.email,
error,
});
captureException(error, undefined, user.email);
}
captureException(error, undefined, email);
});
};

const resend = createResendContact({ email: user.email }).catch((error) => {
logger.error("Error creating Resend contact", {
email: user.email,
error,
});
captureException(error, undefined, user.email);
await createLoopsContact(
email,
name?.split(" ")?.[0],
account?.provider,
).catch((error) => {
const alreadyExists =
error instanceof Error && error.message.includes("409");
if (!alreadyExists) {
logger.error("Error creating Loops contact", {
email,
error,
});
captureException(error, undefined, email);
}
});
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fragile error handling for duplicate contact detection.

The error check on lines 181-183 uses error.message.includes("409") to detect duplicate contacts, which is fragile and could break if the error message format changes.

Consider checking the HTTP status code directly if the error object provides it:

-    const alreadyExists =
-      error instanceof Error && error.message.includes("409");
+    const alreadyExists =
+      (error as any)?.response?.status === 409 ||
+      (error instanceof Error && error.message.includes("409"));

Alternatively, check the Loops API client documentation to see if it throws a specific error type for conflicts.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/web/utils/auth.ts around lines 162 to 191, the duplicate-contact
detection is fragile because it checks error.message.includes("409"); instead,
inspect the error object for a concrete status/code or specific error type: if
the Loops client or HTTP client exposes error.status or error.response?.status,
check that === 409 (or use the client’s Conflict error class), or import and use
the Loops-specific error type/utility to detect conflicts; update the catch to
branch on that status/type and only log/capture non-conflict errors.

@elie222 elie222 merged commit 394134b into main Dec 9, 2025
15 of 16 checks passed
@elie222 elie222 deleted the fix/post-signup branch December 18, 2025 23:06
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