From 4c6d34e86819452208a1c7a47b9a9ee541aa5c3a Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Fri, 16 Oct 2026 00:32:42 -0400 Subject: [PATCH] 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. --- src/lib/realtime/bus.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/lib/realtime/bus.ts b/src/lib/realtime/bus.ts index 463c85bb..30c90fe9 100644 --- a/src/lib/realtime/bus.ts +++ b/src/lib/realtime/bus.ts @@ -5,7 +5,21 @@ export interface SSEEventClient { presenceChannel?: string; } -const clients = new Set(); +/** + * 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; +} +const globalBus = globalThis as typeof globalThis & BusRegistry; +const clients: Set = (globalBus.__ptfSseClients ??= new Set()); export function subscribe(client: SSEEventClient): () => void { clients.add(client);