Skip to content

Commit

Permalink
feat: add bot detection to avoid segment tracking (#958)
Browse files Browse the repository at this point in the history
* feat: add bot detection to avoid segment tracking

* fix: always trigger callback after segment or track

---------

Co-authored-by: Braian Mellor <braianj@gmail.com>
  • Loading branch information
subzet and braianj authored Feb 7, 2025
1 parent 81409a7 commit f8e8152
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@
"html-escaper": "^3.0.3",
"htmlmin": "0.0.7",
"http-proxy-middleware": "^2.0.6",
"isbot": "^5.1.22",
"juice": "^8.0.0",
"lodash": "^4.17.21",
"mime": "^3.0.0",
Expand Down
14 changes: 12 additions & 2 deletions src/utils/development/segment.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isbot } from 'isbot'

import { getMouseEventData, getMouseEventName, isMeta } from '../dom/events'
import { isBlankTarget, isLocalLink } from '../dom/links'
import once from '../function/once'
Expand Down Expand Up @@ -42,7 +44,11 @@ const getContext = once((): TrackContext => {
})

export default function segment(tracker: Tracker, callback?: () => void) {
if (typeof window !== 'undefined' && window.analytics) {
const userAgent = window.navigator.userAgent

const isBot = isbot(userAgent)

if (typeof window !== 'undefined' && window.analytics && !isBot) {
tracker(window.analytics, getContext(), callback ?? emptyCallback)
} else if (callback) {
Promise.resolve().then(() => callback())
Expand All @@ -54,7 +60,11 @@ export function track(
data: Record<string, any> = {},
callback?: () => void
) {
if (typeof window !== 'undefined' && window.analytics) {
const userAgent = window.navigator.userAgent

const isBot = isbot(userAgent)

if (typeof window !== 'undefined' && window.analytics && !isBot) {
const analytics = window.analytics
analytics.track(event, { ...getContext(), ...data }, callback)
} else if (callback) {
Expand Down

0 comments on commit f8e8152

Please sign in to comment.