@analytics/visitor-source — Get visitor source. One of the small, focused utility packages that power the analytics library, usable standalone.
Full documentation, synced from the package README:
A tiny utility library for getting visitor source in 1.17kb.
Exposes getReferrer, isExternalReferrer, getVisitorSource, & parseReferrer functions.
This library will work with analytics or as a standalone import in your code.
Install @analytics/visitor-source from npm.
npm install @analytics/visitor-sourceBelow is the api for @analytics/visitor-source. You can import only what you need & the rest will be tree-shaken out of your bundle.
getReferrerGet the referrer. Falls back to document.referrer in the browser when no referrer is provided.
import { getReferrer } from '@analytics/visitor-source'
const referrer = getReferrer()
console.log('referrer', referrer)
// Or pass an explicit referrer
const ref = getReferrer('https://twitter.com/DavidWells')
console.log('ref', ref)isExternalReferrerCheck if the referrer is external to the current url.
import { isExternalReferrer } from '@analytics/visitor-source'
const external = isExternalReferrer('https://twitter.com/DavidWells', 'https://mysite.com/page')
console.log('external', external) // truegetVisitorSourceGet parsed visitor source data. Accepts an optional referrer, currentUrl, & mapper function to transform the result.
import { getVisitorSource } from '@analytics/visitor-source'
const source = getVisitorSource({
referrer: 'https://twitter.com/DavidWells',
currentUrl: 'https://mysite.com/landing?utm_source=twitter&utm_medium=social',
mapper: (data) => data
})
console.log('source', JSON.stringify(source, null, 2))parseReferrerParse a referrer & current url into structured referral data (type, entry, referrer, & source data).
import { parseReferrer } from '@analytics/visitor-source'
const refData = parseReferrer('https://www.google.com/', 'https://mysite.com/page')
console.log('refData', JSON.stringify(refData, null, 2))
/*
{
type: 'search',
date: '...',
entry: { url: '...', search: '', hash: '' },
referrer: { url: '...', hostname: 'www.google.com', domain: 'google.com', ... },
data: { term: '(not provided)', name: 'google' }
}
*/