Created
September 16, 2016 16:32
-
-
Save ccnixon/7fe6347e93e1f8935c3d9b293974166c to your computer and use it in GitHub Desktop.
Segment.com server side page call with Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express' | |
import Analytics from 'analytics-node' | |
import { stringify } from 'qs' | |
const app = express() | |
const analytics = new Analytics('write-key') | |
app.use((req, res, next) => { | |
const { query, cookies, url, path, ip, host } = req | |
// populate campaign object with any utm params | |
const campaign = {} | |
if (query.utm_content) campaign.content = query.utm_content | |
if (query.utm_campaign) campaign.name = query.utm_campaign | |
if (query.utm_medium) campaign.medium = query.utm_medium | |
if (query.utm_source) campaign.source = query.utm_source | |
if (query.utm_term) campaign.keyword = query.utm_term | |
// grab userId if present | |
let userId = null | |
if (cookies.ajs_user_id) userId = cookies.ajs_user_id | |
// if no anonymousId, send a randomly generated one | |
// otherwise grab existing to include in call to segment | |
let anonymousId | |
if (cookies.ajs_anonymous_id) { | |
anonymousId = cookies.ajs_anonymous_id | |
} else { | |
anonymousId = = uuid.v4() | |
res.cookie('ajs_anonymous_id', anonymousId ) | |
} | |
const referrer = req.get('Referrer') | |
const userAgent = req.get('User-Agent') | |
const properties = { | |
query: stringify(query) | |
referrer, | |
path, | |
host, | |
url | |
/* ++ any custom props (eg. title) */ | |
} | |
const context = { | |
campaign, | |
userAgent, | |
ip | |
} | |
// send a call to segment | |
analytics.page( | |
anonymousId, // either random (matching cookie) or from client | |
userId, // might be null | |
properties, | |
context | |
) | |
// proceed! | |
next() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment