📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
import _includes from 'lodash/includes'
import {
init,
getProfileId,
getSessionId,
startSessionReplay,
track,
trackError as swetrixTrackError,
trackErrors as swetrixTrackErrors,
trackViews as swetrixTrackViews,
type IErrorEventPayload,
type IPageViewPayload,
type TrackEventOptions,
} from 'swetrix'
import { isBrowser, isDevelopment, isSelfhosted } from '~/lib/constants'
export const SWETRIX_PID = 'STEzHcB1rALV'
const SWETRIX_API_PROXY_PATH = '/_internal_data_inngest_proxy'
const REVENUE_ATTRIBUTION_TIMEOUT_MS = 2_000
const isIframe = isBrowser ? window.self !== window.top : false
type SessionReplayActions = Awaited<ReturnType<typeof startSessionReplay>>
let sessionReplayActions: SessionReplayActions | null = null
let sessionReplayStart: Promise<SessionReplayActions | null> | null = null
const REFS_TO_IGNORE = [
/https:\/\/swetrix.com\/(?:[^/]+\/)?projects\/(?!new$)[^/]+$/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?projects\/settings/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?verify/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?password-reset/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?change-email/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?share/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?captchas\/(?!new$)[^/]+$/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?captchas\/settings/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?organisations\/[^/]+/i,
/https:\/\/swetrix.com\/(?:[^/]+\/)?signup\/invitation\/[^/]+/i,
]
const PATHS_REPLACEMENT_MAP = [
{
regex: /^\/(?:[^/]+\/)?projects\/(?!new$)[^/]+$/i,
replacement: '/projects/[id]',
},
{
regex: /^\/(?:[^/]+\/)?projects\/settings/i,
replacement: '/projects/settings/[id]',
},
{
regex: /^\/(?:[^/]+\/)?verify/i,
replacement: '/verify/[token]',
},
{
regex: /^\/(?:[^/]+\/)?password-reset/i,
replacement: '/password-reset/[token]',
},
{
regex: /^\/(?:[^/]+\/)?change-email/i,
replacement: '/change-email/[token]',
},
{
regex: /^\/(?:[^/]+\/)?reports-unsubscribe/i,
replacement: '/reports-unsubscribe/[token]',
},
{
regex: /^\/(?:[^/]+\/)?share/i,
replacement: '/share/[token]',
},
{
regex: /^\/(?:[^/]+\/)?projects\/([^/]+)\/alerts\/create/i,
replacement: '/projects/[id]/alerts/create',
},
{
regex: /^\/(?:[^/]+\/)?projects\/([^/]+)\/subscribers\/invite/i,
replacement: '/projects/[id]/subscribers/invite',
},
{
regex: /^\/(?:[^/]+\/)?projects\/([^/]+)\/alerts\/settings/i,
replacement: '/projects/[id]/alerts/settings/[alert]',
},
{
regex: /^\/(?:[^/]+\/)?projects\/([^/]+)\/password/i,
replacement: '/projects/[id]/password',
},
{
regex: /^\/(?:[^/]+\/)?organisations\/[^/]+/i,
replacement: '/organisations/[id]',
},
{
regex: /^\/(?:[^/]+\/)?signup\/invitation\/[^/]+/i,
replacement: '/signup/invitation/[id]',
},
]
const checkIgnore = (path: string | undefined | null, ignore: RegExp[]) => {
if (!path) {
return false
}
for (let i = 0; i < ignore.length; ++i) {
if (ignore[i].test(path)) {
return true
}
}
return false
}
const getNewPath = (path: string | undefined | null) => {
if (!path) {
return path
}
for (let i = 0; i < PATHS_REPLACEMENT_MAP.length; ++i) {
const map = PATHS_REPLACEMENT_MAP[i]
if (map.regex.test(path)) {
return map.replacement
}
}
return path
}
const startSessionReplayTracking = async () =>
startSessionReplay({
privacy: 'normal',
})
init(SWETRIX_PID, {
disabled: isDevelopment,
apiURL: isSelfhosted ? undefined : SWETRIX_API_PROXY_PATH,
events: {
outboundLinks: true,
},
})
export const trackViews = () => {
if (isSelfhosted || !isBrowser || isDevelopment || isIframe) {
return
}
swetrixTrackViews({
callback: ({ pg, ref }) => {
const result = {
pg,
ref,
} as IPageViewPayload
if (pg?.includes('/demo')) {
return false
}
result.pg = getNewPath(pg)
if (checkIgnore(ref, REFS_TO_IGNORE)) {
result.ref = undefined
}
return result
},
heartbeatOnBackground: true,
})
}
export const trackSessionReplay = () => {
if (isSelfhosted || !isBrowser || isDevelopment || isIframe) {
return
}
if (sessionReplayActions || sessionReplayStart) {
return
}
sessionReplayStart = startSessionReplayTracking()
.then(async (actions) => {
if (!actions) {
return null
}
sessionReplayActions = actions
return actions
})
.catch((reason) => {
console.error('Failed to start Swetrix session replay:', reason)
return null
})
.finally(() => {
sessionReplayStart = null
})
}
export const trackErrors = () => {
if (isSelfhosted || !isBrowser || isDevelopment || isIframe) {
return
}
swetrixTrackErrors({
callback: ({ message, pg, filename }) => {
if (_includes(message, 'Minified React error')) {
return false
}
// 3rd party extension errors
if (
_includes(filename, 'chrome-extension://') ||
_includes(filename, 'moz-extension://')
) {
return false
}
return {
pg: getNewPath(pg),
}
},
})
}
export const trackError = (payload: IErrorEventPayload) => {
if (isSelfhosted || !isBrowser || isDevelopment || isIframe) {
return
}
swetrixTrackError(payload)
}
export const trackCustom = (ev: string, meta?: TrackEventOptions['meta']) => {
if (isSelfhosted || !isBrowser || isDevelopment || isIframe) {
return
}
track({
ev,
meta,
}).catch((reason) => {
console.error('Failed to track custom event:', reason)
})
}
export const getRevenueAttribution = async (): Promise<{
swetrixProfileId?: string
swetrixSessionId?: string
}> => {
if (isSelfhosted || !isBrowser || isIframe) {
return {}
}
let timeoutId: ReturnType<typeof setTimeout> | undefined
try {
const attributionPromise = Promise.all([getProfileId(), getSessionId()])
const timeoutPromise = new Promise<null>((resolve) => {
timeoutId = setTimeout(
() => resolve(null),
REVENUE_ATTRIBUTION_TIMEOUT_MS,
)
})
const attribution = await Promise.race([attributionPromise, timeoutPromise])
if (!attribution) {
return {}
}
const [profileId, sessionId] = attribution
return {
...(profileId ? { swetrixProfileId: profileId } : {}),
...(sessionId ? { swetrixSessionId: sessionId } : {}),
}
} catch (reason) {
console.error('Failed to get revenue attribution:', reason)
return {}
} finally {
if (timeoutId) {
clearTimeout(timeoutId)
}
}
}