Skip to content

📈 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!

Server side pageviews tracking

Blue Mouse797fdec70914
diff --git a/web/app/pages/Blog/Post.tsx b/web/app/pages/Blog/Post.tsx
index bf1c1bac2..2d86df9fb 100644
--- a/web/app/pages/Blog/Post.tsx
+++ b/web/app/pages/Blog/Post.tsx
@@ -1,11 +1,9 @@
import { CaretLeftIcon } from '@phosphor-icons/react'
-import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useLoaderData, useLocation } from 'react-router'
+import { Link, useLoaderData } from 'react-router'
import ExitIntentPopup from '~/components/ExitIntentPopup'
import NotFound from '~/pages/NotFound'
-import { trackPageview } from '~/utils/analytics'
interface Post {
slug: string
@@ -20,25 +18,9 @@ interface Post {
}
export default function PostSlug() {
- const location = useLocation()
const post = useLoaderData() as Post
const { 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.tsx
index 24cd44249..6ad0389cf 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -41,7 +41,8 @@ import {
} from '~/lib/constants'
import mainCss from '~/styles/index.css?url'
import tailwindCss from '~/styles/tailwind.css?url'
-import { trackViews, trackErrors, trackError } from '~/utils/analytics'
+import { trackErrors, trackError } from '~/utils/analytics'
+import { isBlogPostPath, trackPageview } from '~/utils/analytics.server'
import { getCookie } from '~/utils/cookie'
import { detectTheme, isWWW } from '~/utils/server'
import { createHeadersWithCookies, hasAuthTokens } from '~/utils/session.server'
@@ -51,7 +52,6 @@ import { detectLanguage } from './i18n'
import { AuthProvider } from './providers/AuthProvider'
import { ThemeProvider, useTheme } from './providers/ThemeProvider'
-trackViews()
trackErrors()
declare global {
@@ -221,6 +221,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect(httpToHttps, 301)
}
+ if (!isBlogPostPath(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/blog.$category.$slug.tsx b/web/app/routes/blog.$category.$slug.tsx
index 165666f8c..cb2905b4e 100644
--- a/web/app/routes/blog.$category.$slug.tsx
+++ b/web/app/routes/blog.$category.$slug.tsx
@@ -8,6 +8,7 @@ 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'
@@ -47,6 +48,14 @@ 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.tsx
index be278a48d..2d4dce675 100644
--- a/web/app/routes/blog.$slug.tsx
+++ b/web/app/routes/blog.$slug.tsx
@@ -13,6 +13,7 @@ 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'
@@ -95,6 +96,14 @@ 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.ts
index 7a88dd025..8f8c2a3a4 100644
--- a/web/app/utils/analytics.server.ts
+++ b/web/app/utils/analytics.server.ts
@@ -1,6 +1,6 @@
-import { Swetrix } from '@swetrix/node'
+import { Swetrix, type TrackPageViewOptions } from '@swetrix/node'
-import { SWETRIX_PID } from '~/utils/analytics'
+import { SWETRIX_PID, PATHS_REPLACEMENT_MAP } from '~/utils/analytics'
import { isSelfhosted, isDevelopment, API_URL } from '~/lib/constants'
import { getClientIP } from '~/api/api.server'
@@ -10,8 +10,79 @@ 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 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)
+
+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 pg = getNewPath(options.pg || url.pathname)
+ 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.ts
index d68b9f4b6..e72cf5024 100644
--- a/web/app/utils/analytics.ts
+++ b/web/app/utils/analytics.ts
@@ -1,28 +1,11 @@
import _includes from 'lodash/includes'
import * as Swetrix from 'swetrix'
-import {
- isBrowser,
- isDevelopment,
- isIframe,
- isSelfhosted,
-} from '~/lib/constants'
+import { isBrowser, isDevelopment, isSelfhosted } from '~/lib/constants'
export const SWETRIX_PID = 'STEzHcB1rALV'
-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 PATHS_REPLACEMENT_MAP = [
+export const PATHS_REPLACEMENT_MAP = [
{
regex: /^\/projects\/(?!new$)[^/]+$/i,
replacement: '/projects/[id]',
@@ -77,20 +60,6 @@ const PATHS_REPLACEMENT_MAP = [
},
]
-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
@@ -111,49 +80,6 @@ Swetrix.init(SWETRIX_PID, {
disabled: isDevelopment,
})
-const BLOG_PAGE_REGEX = /^\/blog\/.+$/
-
-export const trackViews = () => {
- if (isSelfhosted || !isBrowser || isIframe || isDevelopment) {
- return
- }
-
- Swetrix.trackViews({
- callback: ({ pg, ref }) => {
- const locale = window?.REMIX_ENV?.LOCALE || 'N/A'
-
- const result = {
- pg,
- ref,
- meta: {
- locale,
- },
- } 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) {
return