Skip to content

Tanstack Start: Allow prefetching data for useSpacetimeDBQuery #4438

@vaneworks

Description

@vaneworks

Problem
There's no way to preload data server-side and hand off to real-time subscriptions on the client. This is a blocker for any app where SEO is a hard requirement — search crawlers need to see rendered content in the initial HTML.

It's possible to seed the React Query cache during SSR using the HTTP SQL endpoint and the query key format ['spacetimedb', tableName, sql]. Data renders on first paint with no loading state. However, mutations aren't reactive afterwards because the WebSocket subscription never gets created.

Root cause
SpacetimeDBQueryClient.queryFn is the only code path that calls setupSubscription. If the cache is already populated from SSR with staleTime: Infinity, React Query never calls queryFn, so no subscription is created.

Suggestion
It would be great to have a first-party API for preloading both tables and views, something like:

// Server: prefetch a table or view
const people = await spacetimedb.prefetch(tables.person);
const topPlayers = await spacetimedb.prefetch(views.topPlayers);

// Client: use prefetched data, automatically sets up subscription
const [people] = useSpacetimeDBQuery(tables.person, { prefetchedData: people });
const [topPlayers] = useSpacetimeDBQuery(views.topPlayers, { prefetchedData: topPlayers });

The table/view references already know their SQL and query keys. The SDK is in the best position to handle the HTTP response format, query key alignment, and subscription handoff — for both tables and views — rather than having users wire this up manually.

Since the useSpacetimeDBQuery hook is already built on top of react query and react query lets you preload queries, surely this should be a staple derived feature.

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