diff --git a/.changeset/poor-crabs-drum.md b/.changeset/poor-crabs-drum.md new file mode 100644 index 0000000000..db46209220 --- /dev/null +++ b/.changeset/poor-crabs-drum.md @@ -0,0 +1,5 @@ +--- +"blitz": patch +--- + +blitz-rpc: Cleanup Event Listeners - Fix potential memory leak by cleaning up any residual event listeners set by blitz. diff --git a/packages/blitz/src/global.ts b/packages/blitz/src/global.ts index 2e00179525..be6f7b723a 100644 --- a/packages/blitz/src/global.ts +++ b/packages/blitz/src/global.ts @@ -5,4 +5,5 @@ declare global { beforeHttpRequest: BeforeHttpRequest beforeHttpResponse: BeforeHttpResponse } + var __BLITZ_CLEAN_UP_LISTENERS: () => void } diff --git a/packages/blitz/src/plugin.ts b/packages/blitz/src/plugin.ts index af10246c44..1a1f6d180d 100644 --- a/packages/blitz/src/plugin.ts +++ b/packages/blitz/src/plugin.ts @@ -89,13 +89,23 @@ export function reduceBlitzClientPlugins { + if (globalThis.__BLITZ_CLEAN_UP_LISTENERS) { + globalThis.__BLITZ_CLEAN_UP_LISTENERS() + } + const onSessionCreated = async () => { await Promise.all(events.onSessionCreated()) - }) - document.addEventListener("blitz:rpc-error", async (e) => { + } + const onRpcError = async (e: Event): Promise => { const customEvent = e as CustomEvent await Promise.all(events.onRpcError(customEvent.detail)) - }) + } + document.addEventListener("blitz:session-created", onSessionCreated) + document.addEventListener("blitz:rpc-error", onRpcError) + + globalThis.__BLITZ_CLEAN_UP_LISTENERS = () => { + document.removeEventListener("blitz:session-created", onSessionCreated) + document.removeEventListener("blitz:rpc-error", onRpcError) + } } const withPlugins = compose(...providers)