Express middleware for Google Universal Analytics
npm install express-universal-analyticsThis 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.


```
npm install --save express-universal-analytics
- 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
- This needs session management to be able to save and persist the uid
- Which means req.session must be availablereq.session
- Robust session management is not required, paltry memory-based sessions will work too
- If is not possible, then create a middleware that runsreq.visitor.event
before all of your calls that would populatereq.visitor.setUid
on every pass.
`javascript
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
You can make this pair up with your frontend tracking
by acquiring the session from the frontend cookie.
`js
// GA on frontend uses a cookie called '_ga
app.use(ExpressGA({
uaCode: 'UA-XXXX-X',
autoTrackPages: false,
cookieName: '_ga',
}))
``_ga
If you pass something else instead of (not recommended) in cookie name, we will make our own separate cookieautoTrackPages
and not use GTag one.
Setting 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.
`js `
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
`js
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')
})
`
on which
you can generate screenview, pageview and events
`js
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')
})
`$3
We can also track transaction events (chain the transaction with items if you want to track items)
`js
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
What it tracks
The middleware automatically tracks the following
| Tracked parameter | Description |
|-------------------|-------------|
| document host | Host of your website with protocol - eg |
| document path | Part of the URL, after the domain name, i.e. /b/c in |
| 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 -
`javascript
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.