PostHog / posthog-js-lite

Reimplementation of posthog-js to be as light and modular as possible.
https://posthog.com/docs/libraries
MIT License
70 stars 36 forks source link

Does not work in Next.js serverless (API route) #255

Closed antoinerousseau closed 2 months ago

antoinerousseau commented 2 months ago

Bug description

SSR support was supported in https://github.com/PostHog/posthog-js-lite/pull/57), but as mentioned here, the web version gets loaded instead of the Node.js version, and it tries to access the window object, throwing a ReferenceError: window is not defined from here, here or here.

How to reproduce

  1. Create a Next.js app router API route
  2. import { PostHog } from "posthog-js-lite"
    export async function GET() {
    const posthog = new PostHog(...)
    posthog.capture(...)
    }
  3. Call the API route from a component: you get a ReferenceError: window is not defined

Related sub-libraries

Additional context

Related: https://github.com/PostHog/posthog-js-lite/issues/67#issuecomment-1488735973

benjackwhite commented 2 months ago

This lib really isn't designed for the use case in mind. Next-js router API is running server side and as such is basically a node-js environment and so should use the built posthog-node target instead as that way it includes concepts such as graceful shutdown and the correct fetch implementation for your node environment.