npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-universal-analytics

v0.7.1

Published

Express middleware for Google Universal Analytics

Downloads

3

Readme

Express Universal Analytics

This is an express middleware to enable Google Universal Analytics page tracking on your server. You can use this with server-served pages, or any custom route events.

TypeScript

NPM

Install

npm install --save express-universal-analytics

Requirements

GA Cookie Reading

  • If you read GA cookie, then it is important your frontend actually is even sending it
  • If you're making AJAX calls, make sure it is withCredentials

Session

  • This needs session management to be able to save and persist the uid
  • Which means req.session must be available
  • Robust session management is not required, paltry memory-based sessions will work too
  • If req.session is not possible, then create a middleware that runs before all of your req.visitor.event calls that would populate req.visitor.setUid on every pass.

Usage

Basic (auto page-view)

To simply track page views use this -

import * as express from 'express'
import { Request } from 'express'
import ExpressGA from 'express-universal-analytics'

const app = express();

app.use(ExpressGA('UA-XXXXXXX-X'));

app.get('/hello', (req, res) => {
  res.send('Hello World')
})

app.listen(4444)

The middleware will automatically be tracking all page views

Advanced (cookie and userid setup)

You can make this pair up with your frontend tracking by acquiring the session from the frontend cookie.

// GA on frontend uses a cookie called '_ga`
app.use(ExpressGA({
  uaCode: 'UA-XXXX-X',
  autoTrackPages: false,
  cookieName: '_ga',
}))

If you pass something else instead of _ga (not recommended) in cookie name, we will make our own separate cookie and not use GTag one. Setting autoTrackPages to false will not track pageviews automatically this is something you might want to do if you're adding it to API routes

Also to set userid, there are two ways. If you have a way to extract userid from req object, then pass a reqToUserId function.

app.use(ExpressGA({
  uaCode: 'UA-XXXX-XX', // ga id
  cookieName: '_ga', // cookie name
  reqToUserId: (req) => req.user && req.user.id // extract user id from request
}))

If you have the userid in your context somewhere else, (not in req object), then do this instead

app.use(ExpressGA('UA-XXXXX-X'))

app.get('/somepage', (req, res) => {

  // get the user id 
  const userId = somePlaceToFetchUserIdFrom(x, y, z)

  // set it to visitor
  req.visitor.setUid(userId)

  res.send('Whatever it is')

})

Custom Events

If you also want to generate custom events, we have a req.visitor on which you can generate screenview, pageview and events

app.get('/event', (req: Request, res) => {

  req.visitor.event({
    dp: req.originalUrl,
    ea: 'visit',  // action
    ec: 'route',  // category
    el: 'sample', // label
    ev: 1,        // value
  }).send()

  res.send('Event handled')
})

Custom Transactions

We can also track transaction events (chain the transaction with items if you want to track items)

app.post('/purchase/:productId', (req: Request, res) => {

  req.visitor
  .transaction(
    // transaction id, revenue, shipping, tax, affiliate
    {ti: "trans-12345", tr: 500, ts: 50, tt: 100, ta: "Partner 13"}
  )
  .item(
    // item price, quantity, item code, name and category (iv)
    {ip: 300, iq: 1, ic: "item-54321", in: "Item 54321", iv: "Blue"}
  )
  .item({ip: 200, iq: 2, ic: "item-41325", in: "Item 41325", iv: "XXL"})
  .send()

  res.send('Whatever you do here')
})

Parameters

Documentation for params like dh, dp, uid, ti, tr etc are all available here

https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters

What it tracks

The middleware automatically tracks the following

| Tracked parameter | Description | |-------------------|-------------| | document host | Host of your website with protocol - eg http://cb.lk | | document path | Part of the URL, after the domain name, i.e. /b/c in http://a.com/b/c | | document referer | The website from which the user came from, if any | | user agent | The device/browser/OS used to browse the page | | ip address | The user's ip Address| | campaign name | From the query param utm_campaign | | campaign source | From the query param utm_source | | campaign medium | From the query param utm_medium |

All of this is fetched from the request object. Here is the code basically -

    dp: req.originalUrl,
    dr: req.get('Referer'),
    ua: req.headers['user-agent'],
    uip: req.headers['x-forwarded-for'].split(',').pop()
    || req.connection.remoteAddress
    || req.socket.remoteAddress
    || req.connection.socket.remoteAddress

Thanks

This is a wrapper over the very useful node module universal-analytics which in turn used the http://www.google-analytics.com/collect REST API.