Skip to content

Comments

Add compatibility for Cloudflare Workers#784

Open
Rohan487 wants to merge 3 commits intogram-js:masterfrom
Rohan487:master
Open

Add compatibility for Cloudflare Workers#784
Rohan487 wants to merge 3 commits intogram-js:masterfrom
Rohan487:master

Conversation

@Rohan487
Copy link

Done a few changes to detect the Cloudflare Worker environment and updated the README with usage instructions. Personally tested, this should work.

@Rohan487
Copy link
Author

related #506

@kubk
Copy link
Contributor

kubk commented May 15, 2025

Hi, thank you for testing the library with Cloudflare Workers. It is also something that I am considering trying. What if you use the following approach?

+export const isCloudflareWorker = typeof navigator !== "undefined" ? navigator.userAgent == "Cloudflare-Workers" : false 
-export const isBrowser = !isDeno && typeof window !== "undefined"
+export const isBrowser = isCloudflareWorker || (!isDeno && typeof window !== "undefined")
export const isNode = !isBrowser;

It should reduce the amount of changes needed in the library

@Rohan487
Copy link
Author

Hey! Thanks for the suggestion — it's a thoughtful optimization for reducing code changes. However, I’d like to clarify why treating isCloudflareWorker as part of the isBrowser check can lead to unintended issues.

Cloudflare Workers run in an execution environment that's neither a full browser nor a complete Node.js runtime. It's a runtime similar to a Service Worker, but very limited in API support:

There's no full window object, unlike browsers.

Common browser functions like alert, document, localStorage, and others are not available.

The global scope behaves more like a Web Worker than a traditional browser tab.

If we do something like this:
export const isBrowser = isCloudflareWorker || (!isDeno && typeof window !== "undefined");

It implies that Cloudflare Workers are browser environments, which isn't true. This might cause issues in the library where code assumes full browser features when isBrowser is true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants