📈 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
Back to client side analytics
Blue Mouse1ca95819ec55
diff --git a/web/app/pages/Blog/Post.tsx b/web/app/pages/Blog/Post.tsxindex 2d86df9fb..bf1c1bac2 100644--- a/web/app/pages/Blog/Post.tsx+++ b/web/app/pages/Blog/Post.tsx@@ -1,9 +1,11 @@import { CaretLeftIcon } from '@phosphor-icons/react'+import { useEffect } from 'react'import { useTranslation } from 'react-i18next'-import { Link, useLoaderData } from 'react-router'+import { Link, useLoaderData, useLocation } from 'react-router'import ExitIntentPopup from '~/components/ExitIntentPopup'import NotFound from '~/pages/NotFound'+import { trackPageview } from '~/utils/analytics'interface Post {slug: string@@ -18,9 +20,25 @@ interface Post {}export default function PostSlug() {+ const location = useLocation()const post = useLoaderData() as Postconst { t } = useTranslation('common')+ useEffect(() => {+ const meta = post?.author+ ? {+ author: post.author,+ }+ : undefined++ trackPageview({+ payload: {+ pg: location.pathname,+ meta,+ },+ })+ }, [post, location])+if (!post) {return <NotFound />}diff --git a/web/app/root.tsx b/web/app/root.tsxindex 0dd3adf57..24cd44249 100644--- a/web/app/root.tsx+++ b/web/app/root.tsx@@ -41,12 +41,7 @@ import {} from '~/lib/constants'import mainCss from '~/styles/index.css?url'import tailwindCss from '~/styles/tailwind.css?url'-import { trackErrors, trackError } from '~/utils/analytics'-import {- isBlogPostPath,- isTrackablePagePath,- trackPageview,-} from '~/utils/analytics.server'+import { trackViews, trackErrors, trackError } from '~/utils/analytics'import { getCookie } from '~/utils/cookie'import { detectTheme, isWWW } from '~/utils/server'import { createHeadersWithCookies, hasAuthTokens } from '~/utils/session.server'@@ -56,6 +51,7 @@ import { detectLanguage } from './i18n'import { AuthProvider } from './providers/AuthProvider'import { ThemeProvider, useTheme } from './providers/ThemeProvider'+trackViews()trackErrors()declare global {@@ -225,13 +221,6 @@ export async function loader({ request }: LoaderFunctionArgs) {return redirect(httpToHttps, 301)}- if (- !isBlogPostPath(urlObject.pathname) &&- isTrackablePagePath(urlObject.pathname)- ) {- void trackPageview(request, { pg: urlObject.pathname })- }-const locale = detectLanguage(request)const theme = detectTheme(request)const hasTokens = hasAuthTokens(request)diff --git a/web/app/routes/[_internal_data_inngest_proxy].$.tsx b/web/app/routes/[_internal_data_inngest_proxy].$.tsxnew file mode 100644index 000000000..ad81ceef8--- /dev/null+++ b/web/app/routes/[_internal_data_inngest_proxy].$.tsx@@ -0,0 +1,7 @@+import type { ActionFunctionArgs } from 'react-router'++import { proxySwetrixAnalyticsRequest } from '~/utils/analyticsProxy.server'++export async function action({ request }: ActionFunctionArgs) {+ return proxySwetrixAnalyticsRequest(request)+}diff --git a/web/app/routes/[_internal_data_inngest_proxy].tsx b/web/app/routes/[_internal_data_inngest_proxy].tsxnew file mode 100644index 000000000..ad81ceef8--- /dev/null+++ b/web/app/routes/[_internal_data_inngest_proxy].tsx@@ -0,0 +1,7 @@+import type { ActionFunctionArgs } from 'react-router'++import { proxySwetrixAnalyticsRequest } from '~/utils/analyticsProxy.server'++export async function action({ request }: ActionFunctionArgs) {+ return proxySwetrixAnalyticsRequest(request)+}diff --git a/web/app/routes/blog.$category.$slug.tsx b/web/app/routes/blog.$category.$slug.tsxindex cb2905b4e..165666f8c 100644--- a/web/app/routes/blog.$category.$slug.tsx+++ b/web/app/routes/blog.$category.$slug.tsx@@ -8,7 +8,6 @@ import {isDisableMarketingPages,} from '~/lib/constants'import Post from '~/pages/Blog/Post'-import { trackPageview } from '~/utils/analytics.server'import { getPost } from '~/utils/getPosts.server'import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'@@ -48,14 +47,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {})}- void trackPageview(request, {- meta: post.author- ? {- author: post.author,- }- : undefined,- })-return post}diff --git a/web/app/routes/blog.$slug.tsx b/web/app/routes/blog.$slug.tsxindex 2d4dce675..be278a48d 100644--- a/web/app/routes/blog.$slug.tsx+++ b/web/app/routes/blog.$slug.tsx@@ -13,7 +13,6 @@ import {API_URL,} from '~/lib/constants'import Post from '~/pages/Blog/Post'-import { trackPageview } from '~/utils/analytics.server'import { getSlugFromFilename, getDateFromFilename } from '~/utils/blog'import { getPost } from '~/utils/getPosts.server'import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'@@ -96,14 +95,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {})}- void trackPageview(request, {- meta: post.author- ? {- author: post.author,- }- : undefined,- })-return post}diff --git a/web/app/utils/analytics.server.ts b/web/app/utils/analytics.server.tsindex 2b8cd1e11..7a88dd025 100644--- a/web/app/utils/analytics.server.ts+++ b/web/app/utils/analytics.server.ts@@ -1,6 +1,6 @@-import { Swetrix, type TrackPageViewOptions } from '@swetrix/node'+import { Swetrix } from '@swetrix/node'-import { SWETRIX_PID, PATHS_REPLACEMENT_MAP } from '~/utils/analytics'+import { SWETRIX_PID } from '~/utils/analytics'import { isSelfhosted, isDevelopment, API_URL } from '~/lib/constants'import { getClientIP } from '~/api/api.server'@@ -10,169 +10,8 @@ const swetrix = new Swetrix(SWETRIX_PID, {devMode: isDevelopment,})-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,-]--const BLOG_PAGE_REGEX = /^\/blog\/.+$/-const COMPARISON_PAGE_REGEX = /^\/comparison\/[^/]+\/?$/--const TRACKABLE_STATIC_PATHS = new Set([- '/',- '/dashboard',- '/login',- '/signup',- '/onboarding',- '/projects',- '/open',- '/performance',- '/error-tracking',- '/contact',- '/socialised',- '/google-analytics-alternative',- '/for-startups',- '/for-small-businesses',- '/for-marketers',- '/user-settings',- '/billing',- '/blog',- '/tools',- '/tools/ip-lookup',- '/tools/ctr-calculator',- '/tools/roi-calculator',- '/tools/sitemap-validator',- '/tools/utm-generator',- '/captcha',- '/captcha/demo',- '/organisations',- '/data-policy',- '/cookie-policy',- '/privacy',- '/terms',- '/imprint',-])--const TRACKABLE_DYNAMIC_PATHS = [- /^\/projects\/(?!new$)[^/]+$/i,- /^\/projects\/[^/]+\/subscribers\/invite$/i,- /^\/projects\/settings\/[^/]+$/i,- /^\/verify\/[^/]+$/i,- /^\/password-reset\/[^/]+$/i,- /^\/change-email\/[^/]+$/i,- /^\/share\/[^/]+$/i,- /^\/reports-unsubscribe\/[^/]+$/i,- /^\/3rd-party-unsubscribe\/[^/]+$/i,- /^\/ref\/[^/]+$/i,- /^\/ref\/[^/]+\/[^/]+$/i,- /^\/organisations\/[^/]+$/i,- /^\/organisation\/invite\/[^/]+$/i,-]-const EXPERIMENT_FETCH_TIMEOUT_MS = 5_000-const checkIgnore = (path: string | undefined, 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) => {- 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-}--export const isBlogPostPath = (path: string) => BLOG_PAGE_REGEX.test(path)--const normalizePath = (path: string) => {- if (path.length > 1 && path.endsWith('/')) {- return path.slice(0, -1)- }-- return path-}--export const isTrackablePagePath = (path: string | undefined) => {- if (!path) {- return false- }-- const normalizedPath = normalizePath(path)-- if (- TRACKABLE_STATIC_PATHS.has(normalizedPath) ||- isBlogPostPath(normalizedPath) ||- COMPARISON_PAGE_REGEX.test(normalizedPath)- ) {- return true- }-- for (let i = 0; i < TRACKABLE_DYNAMIC_PATHS.length; ++i) {- if (TRACKABLE_DYNAMIC_PATHS[i].test(normalizedPath)) {- return true- }- }-- return false-}--export const trackPageview = async (- request: Request,- options: TrackPageViewOptions = {},-) => {- if (isSelfhosted || isDevelopment) {- return- }-- try {- const ip = getClientIP(request) || '127.0.0.1'- const userAgent = request.headers.get('user-agent') || ''- const url = new URL(request.url)- const rawPath = options.pg || url.pathname-- if (!isTrackablePagePath(rawPath)) {- return- }-- const pg = getNewPath(rawPath)- const ref = options.ref || request.headers.get('referer') || undefined-- await swetrix.trackPageView(ip, userAgent, {- ...options,- pg,- ref: checkIgnore(ref, REFS_TO_IGNORE) ? undefined : ref,- })- } catch (reason) {- console.error('[analytics.server] Failed to track pageview:', reason)- }-}-export async function getExperimentVariant(request: Request,experimentId: string,diff --git a/web/app/utils/analytics.ts b/web/app/utils/analytics.tsindex e72cf5024..6e3216325 100644--- a/web/app/utils/analytics.ts+++ b/web/app/utils/analytics.ts@@ -4,8 +4,21 @@ import * as Swetrix from 'swetrix'import { isBrowser, isDevelopment, isSelfhosted } from '~/lib/constants'export const SWETRIX_PID = 'STEzHcB1rALV'+const SWETRIX_API_PROXY_PATH = '/_internal_data_inngest_proxy'++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,+]-export const PATHS_REPLACEMENT_MAP = [+const PATHS_REPLACEMENT_MAP = [{regex: /^\/projects\/(?!new$)[^/]+$/i,replacement: '/projects/[id]',@@ -60,6 +73,22 @@ export const PATHS_REPLACEMENT_MAP = [},]+const BLOG_PAGE_REGEX = /^\/blog\/.+$/++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@@ -78,8 +107,45 @@ const getNewPath = (path: string | undefined | null) => {Swetrix.init(SWETRIX_PID, {disabled: isDevelopment,+ apiURL: isSelfhosted ? undefined : SWETRIX_API_PROXY_PATH,})+export const trackViews = () => {+ if (isSelfhosted || !isBrowser || isDevelopment) {+ return+ }++ Swetrix.trackViews({+ callback: ({ pg, ref }) => {+ const result = {+ pg,+ ref,+ } as Swetrix.IPageViewPayload++ if (pg && BLOG_PAGE_REGEX.test(pg)) {+ return false+ }++ result.pg = getNewPath(pg)++ if (checkIgnore(ref, REFS_TO_IGNORE)) {+ result.ref = undefined+ }++ return result+ },+ heartbeatOnBackground: true,+ })+}++export const trackPageview = (options: Swetrix.IPageviewOptions) => {+ if (isSelfhosted) {+ return+ }++ Swetrix.pageview(options)+}+export const trackErrors = () => {if (isSelfhosted || !isBrowser || isDevelopment) {returndiff --git a/web/app/utils/analyticsProxy.server.ts b/web/app/utils/analyticsProxy.server.tsnew file mode 100644index 000000000..1a7eda32b--- /dev/null+++ b/web/app/utils/analyticsProxy.server.ts@@ -0,0 +1,66 @@+const SWETRIX_API_BASE_URL = 'https://api.swetrix.com/log'+const PROXY_BASE_PATH = '/_internal_data_inngest_proxy'+const SWETRIX_PID = 'STEzHcB1rALV'++const jsonError = (status: number, error: string) =>+ new Response(JSON.stringify({ error }), {+ status,+ headers: {+ 'Content-Type': 'application/json',+ },+ })++const buildTargetUrl = (requestUrl: string) => {+ const url = new URL(requestUrl)+ const pathWithoutBase = url.pathname.startsWith(PROXY_BASE_PATH)+ ? url.pathname.slice(PROXY_BASE_PATH.length)+ : url.pathname+ const normalizedPath = pathWithoutBase.startsWith('/')+ ? pathWithoutBase+ : `/${pathWithoutBase}`++ return `${SWETRIX_API_BASE_URL}${normalizedPath}${url.search}`+}++export const proxySwetrixAnalyticsRequest = async (request: Request) => {+ if (request.method !== 'POST') {+ return jsonError(405, 'Method Not Allowed')+ }++ const targetUrl = buildTargetUrl(request.url)+ const headers = new Headers(request.headers)+ const bodyText = await request.text()++ headers.delete('host')+ headers.delete('content-length')++ if (!bodyText) {+ return jsonError(400, 'Missing request body')+ }++ let payload: unknown+ try {+ payload = JSON.parse(bodyText)+ } catch {+ return jsonError(400, 'Invalid JSON payload')+ }++ const pid =+ typeof payload === 'object' && payload !== null && 'pid' in payload+ ? (payload as { pid?: unknown }).pid+ : undefined++ if (typeof pid !== 'string') {+ return jsonError(400, 'Missing pid in payload')+ }++ if (pid !== SWETRIX_PID) {+ return jsonError(403, 'Invalid pid')+ }++ return fetch(targetUrl, {+ method: request.method,+ headers,+ body: bodyText,+ })+}