Closed marchellodev closed 1 year ago
I don't think the library supports other runtimes than Node.js at the moment.
And isn't Cloudflare Pages meant for static content? Wouldn't you need Cloudfare Workers instead?
@weyert Cloudflare Pages has been capable of running server-side apps using Workers for some time now (competing against Vercel and the likes). As it currently stands, posthog doesn't work with Workers or any non-node runtime which is a bummer. The biggest issue appears to be the use of the crypto
library, which even with the node-compat
compatibility flag on can't get properly polyfilled. There are solutions to this, but they would either require
1) Cloudflare going out of their way to engineer 100% compatibility with node APIs
2) Posthog using a runtime-independent crypto library or the Web Crypto API, which is now supported natively in Node.js too
With many more alternative runtimes gaining traction (deno, bun, Fastly V8 etc.), I'd suggest switching out the crypto library.
Having the same issue with posthog-node
and I second the comment above by @3x071c.
I tried switching to posthog-js-lite
but it throws a "window is not defined" at runtime so it sounds like it's not ready for node?
@3x071c If you switch out crypto for Webcrypto which would need to be polyfilled for Node v14.
Wouldn't you still have issues with Axios?
We're using PostHog with posthog-node
in Workers. I've made library to fix issues like with crypto
: https://github.com/bubblydoo/cloudflare-workers-compat
It only works with esbuild, but I see that's what you're using as well.
@weyert PostHog takes a fetch
argument:
new PostHog({
fetch: (...args) => fetch(...args)
})
I have verified that this works in Next.js, but I'm not 100% sure this will work in Cloudflare Pages, so it would be nice if someone could verify it works in the latest version.
Please make sure to use:
new PostHog({
fetch: (...args) => fetch(...args)
})
Just FYI—you need to make sure to use waitUntil
when closing the client (by default, Cloudflare shuts down the worker after sending the response; we have to tell it to send the response immediately but continue executing the shutdown promise). So the most idiomatic version of the above should be:
new PostHog(environment.POSTHOG_TOKEN, {
fetch: fetch.bind(globalThis)
});
// Your work here
const response = await fetch("https://www.google.com");
context.waitUntil(posthog.shutdownAsync());
return response;
Bug description
Hello, I am trying to use posthog-node on the backend of Cloudflare pages.
How to reproduce
Related sub-libraries
Additional context
This is the log I get when Cloudflare tries to build my app for its environment: