Skip to content

Race condition when hydrating usePreloadedQuery before Convex client is authenticated (AuthKit) #242

@dpkass

Description

@dpkass

When using WorkOS AuthKit with Convex in a Next.js App Router project, if a query requiring authentication is preloaded on the server (preloadQuery(..., { token })) and then consumed via usePreloadedQuery on the client, the client-side re-subscription sometimes fails because the Convex client has not yet authenticated over its websocket.

Steps to Reproduce

  1. Use preloadQuery(api.secureQuery, {}, { token }) in a Server Component. Make sure api.secureQuery throws on missing token.
  2. Pass it into a Client Component that calls usePreloadedQuery.
  3. Observe: the first render shows data (SSR), but the client re-subscription throws an auth error

Expected Behavior
The Convex React client should wait until it’s authenticated (via the provided useAuth hook) before resubscribing, or at least handle the missing token gracefully.

Workaround
Wrap the client component in an AuthGate that waits for useConvexAuth() to report isLoading === false before mounting the query component.

Environment

  • Next.js (App Router)
  • @workos-inc/authkit-nextjs v2.x
  • convex v1.x
  • Using ConvexProviderWithAuth + useAuth from AuthKit.

Suggested Fix
I'm not sure whether this is an actual bug, or simply intended to be the developers concern. I have the following ideas:

  1. In a normal useQuery I would be able to use "skip", so maybe it's possible to introduce that to usePreloadedQuery aswell.
  2. An options object with a waitForAuth field.
  3. A new primitive function authenticatedQuery or rather a field inside query that indicates, that this particular query needs auth. Then the query would block on server or client while auth is loading (I'm not sure which is more appropriate). Then by default ctx.auth is not available, only if the flag is used.
  4. Similar to the previous, but instead of explicitly defining it, deriving it from the usage of ctx.auth in the function.

Discord Discussion

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions