Skip to content

Fix race condition and migrate converted instant users#43

Merged
mhamann merged 11 commits into
rownd:mainfrom
bcbogdan:feat/supertokens-migrate
Jun 2, 2026
Merged

Fix race condition and migrate converted instant users#43
mhamann merged 11 commits into
rownd:mainfrom
bcbogdan:feat/supertokens-migrate

Conversation

@bcbogdan
Copy link
Copy Markdown
Contributor

@bcbogdan bcbogdan commented Jun 2, 2026

Summary by Sourcery

Extract SuperTokens migration logic into a reusable hook and extend it to handle instant-to-normal user migration, while adding a Next.js example app for validating the flow.

New Features:

  • Introduce a useSuperTokensMigration hook to coordinate Rownd-to-SuperTokens user migration across React and Next.js clients.
  • Add a Next.js example (frontend and backend) demonstrating Rownd-to-SuperTokens lazy migration via @rownd/next.

Bug Fixes:

  • Fix a race condition where SuperTokens migration could be triggered before access tokens or app info were available, and avoid migrating users who remain at the 'instant' auth level.

Enhancements:

  • Refine SuperTokens migration request construction for better error handling and resilience.
  • Update existing SuperTokens migration example dependencies and configuration to use specific plugin versions and current Rownd app keys.

Documentation:

  • Document how to run the new Next.js SuperTokens migration example, including required environment variables and setup steps.

Tests:

  • Add tests for the useSuperTokensMigration hook and Next.js client integration to cover migration behavior and event handling.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Jun 2, 2026

Reviewer's Guide

Refactors SuperTokens migration logic into a reusable hook to avoid race conditions around access token and auth level, wires it into both React and Next.js Rownd providers, and adds a Next.js example app (frontend + backend) to validate Rownd-to-SuperTokens lazy migration behavior while updating existing migration examples and typings.

Sequence diagram for SuperTokens migration via useSuperTokensMigration

sequenceDiagram
    actor User
    participant RowndHub as Rownd_events
    participant Hook as useSuperTokensMigration
    participant Sync as syncUserToSuperTokens
    participant ST as SuperTokens_backend

    User->>RowndHub: sign_in flow
    RowndHub-->>Hook: events.addEventListener(sign_in_completed)
    RowndHub->>Hook: emit sign_in_completed(Event)
    Hook->>Hook: getSignInCompletedUserType(event)
    Hook->>Hook: shouldMigrateSignIn(userType, authLevelRef.current)
    alt shouldMigrateSignIn === true
        Hook->>Hook: pendingMigrationRef.current = true
        Hook->>Hook: flushPendingMigration()
        Hook->>Sync: syncUserToSuperTokens(accessTokenRef.current, supertokensAppInfoRef.current)
        Sync->>ST: POST /auth/plugin/rownd/migrate
    else shouldMigrateSignIn === false
        Hook-->>RowndHub: ignore event
    end

    Hook-->>Hook: useEffect(accessToken, authLevel)
    Hook-->>Hook: useEffect(appInfo)
    Hook->>Hook: flushPendingMigration()
Loading

File-Level Changes

Change Details Files
Extract SuperTokens migration side-effects into a dedicated React hook and use it in the core React provider.
  • Replace inline SuperTokens sync logic in the React provider with useSuperTokensMigration, passing access token, auth level, events, and supertokens config
  • Remove manual refs and sign_in_completed event listener from the provider and type the hub state listener callback with HubListenerProps
src/context/ReactRowndProvider.tsx
src/hooks/useSuperTokensMigration.ts
Integrate the shared SuperTokens migration hook into the Next.js client Rownd integration.
  • Import and call useSuperTokensMigration within the Next.js client, wiring it to useRownd-derived access token, auth level, and events
  • Update the state listener callback to use HubListenerProps typing
src/next/client/index.tsx
Implement race-condition-safe migration logic that handles instant users and appInfo changes.
  • Track access token, auth level, and normalized SuperTokens appInfo in refs and defer migration until all are ready and auth level is non-instant
  • Listen for sign_in_completed events, inspect the event detail in a type-safe way, and only trigger migration for new users or existing instant users
  • Guard CustomEvent access for environments where CustomEvent is undefined
src/hooks/useSuperTokensMigration.ts
Improve robustness of the SuperTokens sync helper and adjust example configs to use fixed versions and required env vars.
  • Move URL and header construction for the migrate endpoint inside the syncUserToSuperTokens try block
  • Make SuperTokens connection URI required in the example backend and pin @supertokens-plugins/rownd-nodejs and @rownd/react dependency versions
src/utils/supertokens-sync.ts
examples/supertokens-migration/backend/src/index.ts
examples/supertokens-migration/backend/package.json
examples/supertokens-migration/frontend/package.json
examples/supertokens-migration/frontend/src/main.tsx
Add a complete Next.js SuperTokens migration example (frontend + backend) for @rownd/next.
  • Create an Express + SuperTokens backend wired with the Rownd plugin and CORS configured for the Next.js frontend and Rownd Hub
  • Add a Next.js App Router frontend using @rownd/next, styled via globals.css, that demonstrates sign-in and shows access tokens
  • Provide project configuration files, env examples, and documentation for running the Next.js migration example
examples/supertokens-migration-nextjs/backend/src/index.ts
examples/supertokens-migration-nextjs/backend/package.json
examples/supertokens-migration-nextjs/backend/tsconfig.json
examples/supertokens-migration-nextjs/backend/.env.example
examples/supertokens-migration-nextjs/backend/.gitignore
examples/supertokens-migration-nextjs/backend/package-lock.json
examples/supertokens-migration-nextjs/frontend/src/app/layout.tsx
examples/supertokens-migration-nextjs/frontend/src/app/page.tsx
examples/supertokens-migration-nextjs/frontend/src/app/globals.css
examples/supertokens-migration-nextjs/frontend/package.json
examples/supertokens-migration-nextjs/frontend/tsconfig.json
examples/supertokens-migration-nextjs/frontend/next.config.ts
examples/supertokens-migration-nextjs/frontend/.env.example
examples/supertokens-migration-nextjs/frontend/.eslintrc.json
examples/supertokens-migration-nextjs/frontend/.gitignore
examples/supertokens-migration-nextjs/frontend/package-lock.json
examples/supertokens-migration-nextjs/README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

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

Hey - I've left some high level feedback:

  • In useSuperTokensMigration, syncUserToSuperTokens is now called without the previous .catch(() => {}) guard, which means network or server errors will surface as unhandled promise rejections; consider adding explicit error handling (e.g., try/catch, logging, or a controlled swallow) to keep behavior consistent and avoid noisy runtime errors.
  • The useEffect that syncs supertokensAppInfoRef in useSuperTokensMigration only depends on appInfo?.appName, appInfo?.apiDomain, and appInfo?.apiBasePath; if other relevant fields are added to appInfo in the future they won’t trigger an update, so it may be more robust to depend on the appInfo object (or supertokens prop) directly.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `useSuperTokensMigration`, `syncUserToSuperTokens` is now called without the previous `.catch(() => {})` guard, which means network or server errors will surface as unhandled promise rejections; consider adding explicit error handling (e.g., try/catch, logging, or a controlled swallow) to keep behavior consistent and avoid noisy runtime errors.
- The `useEffect` that syncs `supertokensAppInfoRef` in `useSuperTokensMigration` only depends on `appInfo?.appName`, `appInfo?.apiDomain`, and `appInfo?.apiBasePath`; if other relevant fields are added to `appInfo` in the future they won’t trigger an update, so it may be more robust to depend on the `appInfo` object (or `supertokens` prop) directly.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

mhamann

This comment was marked as duplicate.

Copy link
Copy Markdown
Contributor

@mhamann mhamann left a comment

Choose a reason for hiding this comment

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

Solid, well-tested refactor: the migration logic is extracted into a clear shouldMigrateSignIn predicate, and the pending/flush pattern is a clean way to defer until the access token + appInfo are ready. The two new tests cover the race fix and the converted-instant path nicely. One correctness question on event ordering that I'd want answered before merge, plus a couple of nits.

Correctness

  • Converted-instant migration depends on event/state ordering — the existing_user path only arms a migration if sign_in_completed is observed while authLevelRef.current is still 'instant'. If the hub propagates auth_level: 'verified' into the ref before the event handler runs, the user is silently skipped. The test forces the favorable ordering by firing the event before the rerender — see the line comment on useSuperTokensMigration.ts:84.

Nits

  • Dropped void in front of the fire-and-forget syncUserToSuperTokens call (line 66). Harmless here since the util swallows its own errors, but it removes the explicit "intentional floating promise" marker. See line comment.
  • flushPendingMigration is recreated each render and called inside three useEffects without being in their dep arrays — react-hooks/exhaustive-deps will flag this. It's fine at runtime (it only reads refs), but worth a // eslint-disable or wrapping in useCallback to keep lint clean.

Tests

  • The two added tests are good. Consider one more guarding the ordering concern above: fire sign_in_completed(existing_user) after the component has already rerendered to authLevel: 'verified', and assert whatever the intended behavior is — that pins down the contract.

Nothing here is a hard blocker; mainly want the ordering question confirmed.

Comment thread src/hooks/useSuperTokensMigration.ts Outdated
Comment thread src/hooks/useSuperTokensMigration.ts Outdated
@mhamann mhamann merged commit 2a1eefe into rownd:main Jun 2, 2026
2 of 3 checks passed
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