Search code examples
node.jsexpressbackendmiddlewaremixpanel

Using Mixpanel - Node Library in Express


I am currently trying integrate the Mixpanel Node library into a test application that I am building. This is a Node.js application using the express framework.

As per the express docs, I have a JS file to manage the project, a folder called "public" that contains all of my static files, and another folder with the node modules that come with express.

I have two static HTML pages in "public" that I am trying to put mixpanel tracking into. I am running the project locally by running node app.js.

app.js includes:

const express = require('express');
const app = express();
const port = 3000;
const path = require('path');

//Mixpanel Additions
var Mixpanel = require('mixpanel');
var mixpanel = Mixpanel.init('<I am putting my project token here>', {
    protocol: 'https'
});

//App Configuration and Init
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/public/page.html'));
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

In my HTML files I try to use mixpanel functions by putting them into script tags:

<script>
mixpanel.track("event")
</script>

But when I run node app.js and view the page in my browser it says:

Uncaught ReferenceError: mixpanel is not defined

I have a pretty poor understanding of node.js, but I am imagining that I need to use app.use(), app.get(), or something along those lines to get the Mixpanel lib loaded into the app. What am I doing wrong? I also realize that my understanding of Express and Node is pretty rudimentary, so any additional knowledge is appreciated, especially if I am way off.


Solution

  • If you want to call mixpanel tracking functions in the browser, you should load the mixpanel library in a script tag on the browser side, as seen here:

    https://developer.mixpanel.com/docs/javascript

    The purpose of the node.js package is to send events from the server side, like if you wanted to log when page.html is rendered, you could do

    app.get('/', (req, res) => {
        res.sendFile(path.join(__dirname + '/public/page.html'));
        mixpanel.track('event')
    });