Skip to content

Prevent a flash after hydration when using auth in SSR #19

@thomasballinger

Description

@thomasballinger

I don't know if there is a flash when using auth with SSR (it's not supported yet, see #18) but if there is:

Say you've got a JWT on the server during SSR: you either spent the network request to exchange the request cookie for one from a third party like Clerk or another server like OpenAuth or the actual JWT is in the cookie.

You'd like to use that token for SSR and on the client, for at least the first few seconds until you get a refreshed on. (to make tokens failing to refresh more obvious, clients shouldn't use this static token for very long).

Your SSR-rendered HTML and subsequent hydration on the client are beautiful! (thx TanStack Query) with all the personalized data rendered. There are now three things you need to avoid to prevent a flash as you transition to live queries:

  1. the client should avoid sending any ModifyQuerySet subscribing messages before sending the Authenticate message since you'll get a flash if useQuery() hooks return empty data or error from running queries without authentication
  2. the client should avoid ever being in the unauthed state where components disappear because of wrappers unmounting them
  3. useQuery() hooks should never return undefined while queries are loading.

(1) we can fix by allowing auth to be passed in during client instantiation. You can't send headers with a WebSocket but we can send an auth message first (possibly a special auth message saying "don't run any queries until you've validated this auth!")
(2) we could fix by changing some hook logic and adding a state like "about to be authed" that counts as authenticated for the purposes of <Authenticated>, <Unauthenticate>, and AuthLoading.
(3) is already solved by TanStack Query's useSuspenseQuery(). In the future the Convex client could solve it by initially loading the client with some query results, TanStack Start makes this easy but several libraries do it in Next.js too.

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