Git Product home page Git Product logo

posthog-node's Introduction

posthog-node's People

Contributors

alexkim205 avatar benjackwhite avatar bitbreakr avatar dependabot[bot] avatar edscode avatar kevinhu avatar liyiy avatar macobo avatar mariusandra avatar neilkakkar avatar tapico-weyert avatar timgl avatar tobiastornros avatar twixes avatar xahhy avatar yakkomajuri avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

posthog-node's Issues

Feature Request: First Time Information if connection is established

Is this related to platform?

No

Describe the Problem

PostHog CLI/SDK throws an error only if we pass an empty string. It doesn't intimate if API Key is valid and the connection is successful or not.

Reason to believe It's required

  • Due to some compliance, If Key needs to change and teams forget to update it in legacy code.
  • Setting Up a New Developing/Staging Environment.

Solution

Asserting an error if the connection is unsuccessful only when the initial connection is made. This should only be for server-side libraries.

Current Approach

Logging a test event (makes no sense every time).

npm install "no such file or directory, chmod"

I am getting an error when trying to npm install on CI:

npm ERR! enoent ENOENT: no such file or directory, chmod '/node_modules/posthog-node/cli.js'

Versions

  • Node: 16
  • Posthog: 2.0.1

InconclusiveMatchError when computing flag locally

Hi.

We've been seing this error a bit randomly in production since we updated from posthog-node 2.2 to 2.4.

Here's a full error example with stack trace:

InconclusiveMatchError when computing flag locally: job-mode-access: Error: Can't determine if feature flag is enabled or not with given properties
      at FeatureFlagsPoller.<anonymous> (/node_app/back/common/node_modules/posthog-node/lib/index.cjs.js:1469:27)
      at step (/node_app/back/common/node_modules/posthog-node/lib/index.cjs.js:140:27)
      at Object.next (/node_app/back/common/node_modules/posthog-node/lib/index.cjs.js:89:53)
      at fulfilled (/node_app/back/common/node_modules/posthog-node/lib/index.cjs.js:70:28)
      at runMicrotasks (<anonymous>)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)

The SDK is initialised with both the API key and personal ApiKey (no identify call) . And we use 2 methods related to FFs: getFeatureFlagValue('ff-key', 'distinct-user-id') and getAllFlags('distinct-user-id').

Calling these methods seems to work fine, we couldn't reproduce any error where we'd get the wrong FF value. Though very little testing was done.
The error seems to come from the SDK's polling logic based on the stack trace, but why would it happen? I couldn't find any documentation about this error.

Cannot find type definition file for 'rusha'

On v3.1.1 I'm getting this error:
image
It is due to the project's tsconfig having 'rusha':

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "types": ["node", "rusha"],
    "typeRoots": ["./node_modules/@types", "../node_modules/@types", "./src/types"]
  }
}

opt_out functionality for posthog-node

Is your feature request related to a problem?

Nope

Describe the solution you'd like

opt_out functionality for posthog-node. This would allow CLIs etc to allow certain users to opt out of analytics.

Describe alternatives you've considered

Right now we are just storing some data locally to show that the user has opted out and avoid calling the client altogether.

Additional context

Thank you for your feature request – we love each and every one!

AbortSignal is not defined

I'm using Posthog node client in the backend of Nuxtjs app and I'm getting these errors in the console.

ERROR  AbortSignal is not defined                                                                                02:55:25

  at PostHogClient.<anonymous> (server.js:1570:17)
  at step (server.js:436:27)
  at Object.next (server.js:385:53)
  at server.js:378:71
  at new Promise (<anonymous>)
  at __awaiter (server.js:364:12)
  at PostHogClient.module.exports.../manifold/node_modules/posthog-node/lib/index.cjs.js.PostHogCore.fetchWithRetry (server.js:1567:16)
  at PostHogClient.<anonymous> (server.js:1314:52)
  at step (server.js:436:27)
  at Object.next (server.js:385:53)

It's a simple getAllFlags() attempt where i'm initializing the client in a Typescript Singleton object. It successfully returns the flags values on page load, but the problem is that I keep getting the above error on each page refresh.

error: uncaughtException: Cannot find module './feature-flags'

When I do,
yarn add posthog-node
inside the node_modules/posthog-node the directory structure is like this,
node_modules clis.js event-validation.js index.d.ts index.js LICENSE package.json README.md

Inside index.js
const { FeatureFlagsPoller } = require('./feature-flags')

there is no './feature-flags' in the folder node_modules/posthog-node/

But here in this Github repo, I see it is there.
How to fix this?

Does not work on the edge [Cloudflare Pages]

Hello, I am trying to use posthog-node on the backend of Cloudflare pages. This is the log I get when Cloudflare tries to build my app for its environment:

14:17:38.143 | > Using @sveltejs/adapter-cloudflare
14:17:38.260 | ✘ [ERROR] Could not resolve "crypto"
14:17:38.260 |  
14:17:38.260 | node_modules/posthog-node/lib/index.esm.js:1:27:
14:17:38.260 | 1 │ import { createHash } from 'crypto';
14:17:38.260 | ╵                            ~~~~~~~~
14:17:38.260 |  
14:17:38.260 | The package "crypto" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.261 |  
14:17:38.292 | ✘ [ERROR] Could not resolve "https"
14:17:38.292 |  
14:17:38.293 | node_modules/gaxios/build/src/gaxios.js:20:24:
14:17:38.293 | 20 │ const https_1 = require("https");
14:17:38.293 | ╵                         ~~~~~~~
14:17:38.293 |  
14:17:38.293 | The package "https" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.293 |  
14:17:38.294 | ✘ [ERROR] Could not resolve "querystring"
14:17:38.294 |  
14:17:38.294 | node_modules/gaxios/build/src/gaxios.js:22:46:
14:17:38.294 | 22 │ const querystring_1 = __importDefault(require("querystring"));
14:17:38.294 | ╵                                               ~~~~~~~~~~~~~
14:17:38.294 |  
14:17:38.294 | The package "querystring" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.295 |  
14:17:38.302 | ✘ [ERROR] Could not resolve "url"
14:17:38.302 |  
14:17:38.303 | node_modules/gaxios/build/src/gaxios.js:24:22:
14:17:38.303 | 24 │ const url_1 = require("url");
14:17:38.303 | ╵                       ~~~~~
14:17:38.303 |  
14:17:38.303 | The package "url" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.303 |  
14:17:38.318 | ✘ [ERROR] Could not resolve "net"
14:17:38.318 |  
14:17:38.319 | node_modules/https-proxy-agent/dist/agent.js:15:38:
14:17:38.319 | 15 │ const net_1 = __importDefault(require("net"));
14:17:38.320 | ╵                                       ~~~~~
14:17:38.320 |  
14:17:38.320 | The package "net" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.320 |  
14:17:38.321 | ✘ [ERROR] Could not resolve "tls"
14:17:38.321 |  
14:17:38.321 | node_modules/https-proxy-agent/dist/agent.js:16:38:
14:17:38.321 | 16 │ const tls_1 = __importDefault(require("tls"));
14:17:38.321 | ╵                                       ~~~~~
14:17:38.321 |  
14:17:38.321 | The package "tls" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.322 |  
14:17:38.322 | ✘ [ERROR] Could not resolve "url"
14:17:38.322 |  
14:17:38.322 | node_modules/https-proxy-agent/dist/agent.js:17:38:
14:17:38.322 | 17 │ const url_1 = __importDefault(require("url"));
14:17:38.322 | ╵                                       ~~~~~
14:17:38.322 |  
14:17:38.322 | The package "url" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.323 |  
14:17:38.323 | ✘ [ERROR] Could not resolve "assert"
14:17:38.323 |  
14:17:38.324 | node_modules/https-proxy-agent/dist/agent.js:18:41:
14:17:38.324 | 18 │ const assert_1 = __importDefault(require("assert"));
14:17:38.324 | ╵                                          ~~~~~~~~
14:17:38.324 |  
14:17:38.324 | The package "assert" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.324 |  
14:17:38.325 | ✘ [ERROR] Could not resolve "events"
14:17:38.325 |  
14:17:38.325 | node_modules/agent-base/dist/src/index.js:5:25:
14:17:38.325 | 5 │ const events_1 = require("events");
14:17:38.325 | ╵                          ~~~~~~~~
14:17:38.325 |  
14:17:38.326 | The package "events" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.
14:17:38.326 |  
14:17:38.338 | error during build:
14:17:38.338 | Error: Build failed with 9 errors:
14:17:38.338 | node_modules/agent-base/dist/src/index.js:5:25: ERROR: Could not resolve "events"
14:17:38.338 | node_modules/gaxios/build/src/gaxios.js:20:24: ERROR: Could not resolve "https"
14:17:38.339 | node_modules/gaxios/build/src/gaxios.js:22:46: ERROR: Could not resolve "querystring"
14:17:38.339 | node_modules/gaxios/build/src/gaxios.js:24:22: ERROR: Could not resolve "url"
14:17:38.339 | node_modules/https-proxy-agent/dist/agent.js:15:38: ERROR: Could not resolve "net"
14:17:38.339 | ...
14:17:38.339 | at failureErrorWithLog (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1604:15)
14:17:38.339 | at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:1056:28
14:17:38.339 | at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:1001:67
14:17:38.339 | at buildResponseToResult (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:1054:7)
14:17:38.339 | at /opt/buildhome/repo/node_modules/esbuild/lib/main.js:1166:14
14:17:38.340 | at responseCallbacks.<computed> (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:701:9)
14:17:38.340 | at handleIncomingPacket (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:756:9)
14:17:38.340 | at Socket.readFromStdout (/opt/buildhome/repo/node_modules/esbuild/lib/main.js:677:7)
14:17:38.340 | at Socket.emit (node:events:513:28)
14:17:38.340 | at addChunk (node:internal/streams/readable:315:12)
14:17:38.369 | Failed: build command exited with code: 1
14:17:39.276 | Failed: an internal error occurred

posthog.getAllFlags not working

Hi. I'm using posthog-node 2.0.2 and I get the following error when calling getAllFlags:

TypeError: undici__default.default.fetch is not a function
    at PostHogClient.fetch (/node_app/back/api/node_modules/@visage/visage-server-common/node_modules/posthog-node/src/posthog-node.ts:53:19)
    at /node_app/back/api/node_modules/@visage/visage-server-common/node_modules/posthog-core/src/index.ts:647:33
    at /node_app/back/api/node_modules/@visage/visage-server-common/node_modules/posthog-core/src/utils.ts:23:25
    at step (/node_app/back/api/node_modules/@visage/visage-server-common/node_modules/node_modules/tslib/tslib.es6.js:102:23)
    at Object.next (/node_app/back/api/node_modules/@visage/visage-server-common/node_modules/node_modules/tslib/tslib.es6.js:83:53)
    at fulfilled (/node_app/back/api/node_modules/@visage/visage-server-common/node_modules/node_modules/tslib/tslib.es6.js:73:58)

PosHog is not a constructor

Hi, I am getting the following error with posthog-node
Here is my package.json file :
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"nodemon": "^2.0.19",
"posthog-node": "^2.0.1"
}
}
Code with posthog in index.js . file :
import PostHog from 'posthog-node'

const client = new PostHog(
'phc_UbdQ93ylhwFK2K2loRAyZrKOKtdNzhyryieuteir',
{ host: 'https://app.posthog.com' } // You can omit this line if using PostHog Cloud
)

client.shutdown()
--> there will be an error message PostHog is not a constructor. Pls help me.

Unable to initialize in Electron app

Problem

It seems the webpack target electron-main can't resolve the axios-retry module correctly.

Unhandled Promise rejection TypeError: axiosRetry is not a function

Is it currently possible to use this library with Electron app? If not, any how to fix the import error?

Axios causing issues when using `post hog-node` in Next.js 12 middleware

Last month Vercel introduced middleware in their latest version of Next.js version 12. The middleware is using edge functions on their hosting environment but when you self-host on example GKE it also works but the same limitations apply.

If I am using posthog-node I am getting the following error:

Error: Error: Request to api/feature_flag failed with error: adapter is not a function
    at FeatureFlagsPoller._request (webpack-internal:///./node_modules/posthog-node/feature-flags.js:158:19)
    at async FeatureFlagsPoller._loadFeatureFlags (webpack-internal:///./node_modules/posthog-node/feature-flags.js:91:25)
    at async FeatureFlagsPoller.loadFeatureFlags (webpack-internal:///./node_modules/posthog-node/feature-flags.js:78:13)
    at async FeatureFlagsPoller.isFeatureEnabled (webpack-internal:///./node_modules/posthog-node/feature-flags.js:36:9)
    at async PostHog.isFeatureEnabled (webpack-internal:///./node_modules/posthog-node/index.js:255:16)
    at async Object.middleware [as handler] (webpack-internal:///./src/pages/_middleware.ts:26:28)
    at async adapter (webpack-internal:///./node_modules/next/dist/server/web/adapter.js:30:22)
    at async DevServer.runMiddleware (/Users/weyertdeboer/Development/Projects/xxx/app/projects/project/node_modules/next/dist/server/next-server.js:438:26)
    at async DevServer.runMiddleware (/Users/weyertdeboer/Development/Projects/xxx/app/projects/project/node_modules/next/dist/server/dev/next-dev-server.js:394:28)
    at async Object.fn (/Users/weyertdeboer/Development/Projects/xxx/app/projects/project/node_modules/next/dist/server/next-server.js:817:34)

I think this due to the use of Axios which is using XMLHttpRequest and this is not supported by the middleware functionality or their edge functions. There is a similar ticket at Next.js discussing this issue: vercel/next.js#30932

I am wondering if it's worth it to rewrite the library in a different library that might use fetch instead my limited scan of the code Axios appears to be mostly used for:

  • retry functionality
  • exponential backoff when retrying
  • throw error for non-ok response
  • automatically handling of json responses

I am happy to raise a PR to make these changes if people at PostHog are happy with this

Issue with dependency

Hi there. I recently posted about an issue I had on Stackoverflow and was advised to share it here as well. I am not 100% confident that Posthog was the source of the problem I had, but after updating my dependencies and removing Posthog, I was able to resolve my issue. As I'm not interested in reintroducing the error, I haven't verified that this issue is coming from Posthog but I figured it might be helpful to post this anyways.

Here's the info from my SO post:

I have a critial issue on my NextJS app where all of the requests to my API routes time out in production. It used to work perfectly up until recently but now my app is unusable (except for the static landing page). It's working perfectly in my local environment.

I'm using NextJS 14.0.1 with App Router; MongoDB + Mongoose

Here are the timed logs from a simple /api/lead endpoint (create a lead in DB)

  • MongoDB Connection: 880.541ms
  • Request JSON Parsing: 0.913ms
  • Finding Lead: 556.57ms
  • Sending Response: 1.31ms

When fetching this through postman, it still takes > 10 seconds for me to receive the response. Default timeout on Netlify / Vercel happens after 10 seconds.

Eventually, my console showed some useful information with the following error:

Compiling /api/auth/[...nextauth] ...
 ⚠ ./node_modules/.pnpm/[email protected][email protected]/node_modules/debug/src/node.js
Module not found: ESM packages (supports-color) need to be imported. Use 'import' to reference the package instead. https://nextjs.org/docs/messages/import-esm-externals

Import trace for requested module:
./node_modules/.pnpm/[email protected][email protected]/node_modules/debug/src/node.js
./node_modules/.pnpm/[email protected][email protected]/node_modules/debug/src/index.js
./node_modules/.pnpm/[email protected][email protected]/node_modules/follow-redirects/debug.js
./node_modules/.pnpm/[email protected][email protected]/node_modules/follow-redirects/index.js
./node_modules/.pnpm/[email protected]/node_modules/axios/dist/node/axios.cjs
./node_modules/.pnpm/[email protected]/node_modules/posthog-node/lib/index.esm.js
./libs/posthog.js
./libs/next-auth.js
./app/api/auth/[...nextauth]/route.js

Like I said, I upgraded all of my dependencies and removed Posthog, and requests came through normally again. Not sure why this issue was only present in my production environment.

Feature Request: Verbose Mode for Development

Is this related to a platform?

No

Describe the Problem.

Currently, there is no way to check, "How data is getting logged?" or "Is there some even triggering by mistake(which was not suppose to happen. of course, coding errors) or more than once(code stuck in a loop for some reason or due to packets on low latency network)?". Keep track of all of those in the PostHog Website is not so great idea while developing, It creates friction.

Solution in Mind

PostHog CLI/SDK to have a "verbose flag" while making the connection to log it into the console. In that way, Developers can have that flag turned on for the developer environment or However they feel it is right. Although This should not affect the functionality of viewing on the PostHog website.

Other Potential Advantages of it

If SDK/CLI is in verbose mode, filter those events on the website automatically.

Approach Currently in use

Manual fastlog and console to check event triggering flow. It's not the best approach for the whole DevOps cycle.

Missing CHANGELOG.md

When a release gets created the commit suggests that CHANGELOG file gets updated but this file doesn't exist. Together with the Releases page only saying Bump version to 1.3.0, update CHANGELOG.md & yarn.lock the only way to find out what has changed is by digging the commit history.

Question: Feature Flags in Server-Side Next.js

Context

Next.js (and many other frameworks) provide methods for server-side rendering/hydrating of React components. In Next, this is achieved by exporting a function called getServerSideProps from the same file as your page component. getServerSideProps can have access to the logged-in user and allows redirects, including out-of-the-box support for 404 pages.

For pages that aren't yet available to the public, I'd like to use a feature flag and the user identity to return the correct props or redirect.

The Problem

It seems that the current posthog-node implementation requires a personal API key with full account access rather than an organizational API key with scoped account access. This seems to imply that API keys are intended to exist for dev/analytics tools for team members and not for production application use.

The Question

Does instantiating posthog-node on the server with a personal API key provide any additional access to the API through the posthog instance?

Uncaught TypeError: posthog_node_1.default is not a constructor

I'm using "typescript": "^3.6.3" with the following tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "sourceMap": true,
    "inlineSources": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  },
  "exclude": ["node_modules", "dist"]
}

When I try to create a new instance of PostHog it gives the following error;

➜  posthog-bug ts-node
> import PostHog from 'posthog-node'

> const client = new PostHog('')
/Users/aras/Work/posthog-bug/<repl>.ts:2
const client = new posthog_node_1.default('');
               ^

Uncaught TypeError: posthog_node_1.default is not a constructor
    at /Users/aras/Work/posthog-bug/<repl>.ts:2:16
    at Script.runInThisContext (vm.js:134:12)
    at runInContext (/Users/aras/.nvm/versions/node/v14.17.6/lib/node_modules/ts-node/src/repl.ts:574:19)
    at Object.execCommand (/Users/aras/.nvm/versions/node/v14.17.6/lib/node_modules/ts-node/src/repl.ts:540:28)
    at /Users/aras/.nvm/versions/node/v14.17.6/lib/node_modules/ts-node/src/repl.ts:562:47
    at Array.reduce (<anonymous>)
    at appendCompileAndEvalInput (/Users/aras/.nvm/versions/node/v14.17.6/lib/node_modules/ts-node/src/repl.ts:562:23)
    at evalCodeInternal (/Users/aras/.nvm/versions/node/v14.17.6/lib/node_modules/ts-node/src/repl.ts:211:12)
    at REPLServer.nodeEval (/Users/aras/.nvm/versions/node/v14.17.6/lib/node_modules/ts-node/src/repl.ts:233:26)
    at bound (domain.js:416:15)
>

When I try to log PostHog, it is undefined

Feature flag poller can throw error when PostHog API return 50xs

Today, we experienced in issue while using the posthog-node library to retrieve feature flags in our backend code. We have the refresh interval enabled to ensure the feature flags get reloaded every n seconds. This polling can throw a runtime error when the backend is return 50x errors like a 502.

For example, the following error:

Error  Request to api/feature_flag failed with error: Request failed with status code 502 
        Error: Request to api/feature_flag failed with error: Request failed with status code 502
   at FeatureFlagsPoller._request (/usr/src/app/node_modules/posthog-node/feature-flags.js:132:19)
   at runMicrotasks ()
   at processTicksAndRejections (internal/process/task_queues.js:95:5)
   at async FeatureFlagsPoller._loadFeatureFlags (/usr/src/app/node_modules/posthog-node/feature-flags.js:75:21)

I would expect the error is handled internally in the FeatureFlagsPoller-class as it gets started automated when initialising the library with the fresh interval

The type definitions are missing `callback`

Looking at the source code (e.g. identify method), many methods have a callback, but in the type definitions the callback is missing.
If someone wanted to await for these methods' callback to be called (not sure if this is the best practice), they would get a compile error.

These methods also return this, but in the type definitions they return void.

Is this intended? Can we update the type definitions with the all the optional prams and correct return types?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.