fix: for more stable broadcast channels on CF workers #2007
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What is this PR?
This PR fixes the below bug (tested on my own fork as previously our worker would sometimes crash, now they don't)
Bug
The BroadcastChannel API is used directly in both
previews.ts
andwebcontainer.preview.$id.tsx
.This will cause a ReferenceError in Cloudflare Workers, since they do not support BroadcastChannel.
Fix Desc
To fix this, ensure that BroadcastChannel is only used in the browser.
This can be done by checking if
typeof BroadcastChannel !== "undefined"
before creating or using it, and by guarding any code that uses it so it does not run in the server/worker environment.Changes
Broadcast Guard
app/lib/stores/previews.ts:23-96
Only create broadcast/storage channels when BroadcastChannel exists, falling back to safer no-ops and logging when the API is missing so worker/server contexts stop throwing.app/lib/stores/previews.ts:158-248
Switched every broadcast path to optional posting so preview refresh/state sync quietly skip when channels are unavailable.app/routes/webcontainer.preview.$id.tsx:48-82
Wrapped the client-side channel setup in a runtime availability check so the Remix loader can execute in Cloudflare Workers without hitting the constructor.