Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plausible with Node.js #432

Closed
ZachSaucier opened this issue Sep 24, 2023 · 1 comment
Closed

Plausible with Node.js #432

ZachSaucier opened this issue Sep 24, 2023 · 1 comment

Comments

@ZachSaucier
Copy link

ZachSaucier commented Sep 24, 2023

Don't use plausible-tracker-node

I mainly wanted to make this post to say don't use plausible-tracker-node. I used it for a few hours successfully then ran into an issue of it throwing unhandled promise errors related to 429 requests even though I was way below Plausible's API maximum.

Node.js + Express.js helper class for Plausible

I ended up writing a little class for Plausible's Events API to use in my Node.js / Express.js app which I might as well share also:

class Plausible {
  domain = "";

  constructor(domain) {
    this.domain = domain;
  }

  trackPageview(req, rest) {
    this.trackEvent("pageview", req, rest);
  }

  trackEvent(name, req, { props, revenue } = {}) {
    const body = {
      domain: this.domain,
      name: name,
      url: `${req.protocol}://${req.get("host")}${req.originalUrl}`,
      referrer: req.get("Referrer"),
    };

    if (props) {
      body.props = props;
    }

    if (revenue) {
      body.revenue = revenue;
    }

    fetch("https://plausible.io/api/event", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Forwarded-For": req.socket.remoteAddress,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    }).catch((err) => console.error("Plausible error", err));
  }
}

Usage:

const plausible = new Plausible(MY_DOMAIN);

plausible.trackPageview(req);

plausible.trackEvent("404", req);
@ruslandoga
Copy link
Collaborator

👋 @ZachSaucier

Self-hosted docs are in the process of being moved to https://github.com/plausible/community-edition

I've re-opened your issue there: plausible/community-edition#94

Sorry for a late reply!

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

No branches or pull requests

2 participants