1
0
Fork 0

feat(realtime): anchor SSE client set on globalThis for cross-bundle delivery

Next.js dev bundles server packages per route, so a module-level Set forks
into one copy per bundle: a broadcast issued from a server action or registry
bundle would never reach a client subscribed through the /api/realtime route
bundle. Anchoring the client set on globalThis unifies every bundle copy within
the single dev process, the same trick blackjack/poker already use. It is a
no-op in production, which has one module instance anyway.
This commit is contained in:
Jason Fraley 2026-10-16 00:32:42 -04:00
parent 49022e6dea
commit 4c6d34e868

View file

@ -5,7 +5,21 @@ export interface SSEEventClient {
presenceChannel?: string;
}
const clients = new Set<SSEEventClient>();
/**
* The connected-client set is anchored on `globalThis`, not module scope. Next.js
* dev bundles server packages per route (`devBundleServerPackages`), so a plain
* module-level Set forks into one copy per bundle: a broadcast issued from a
* server-action or registry bundle would never reach a client subscribed through
* the `/api/realtime` route bundle. Sharing it via `globalThis` (the same trick
* the blackjack/poker stores use, and how Payload caches its instance) unifies
* every bundle within the single dev process. In production there is one module
* instance anyway, so this is a no-op there.
*/
interface BusRegistry {
__ptfSseClients?: Set<SSEEventClient>;
}
const globalBus = globalThis as typeof globalThis & BusRegistry;
const clients: Set<SSEEventClient> = (globalBus.__ptfSseClients ??= new Set<SSEEventClient>());
export function subscribe(client: SSEEventClient): () => void {
clients.add(client);