Skip to content

Commit

Permalink
[WEB] Ensure we're merging anonymous users in MP
Browse files Browse the repository at this point in the history
  • Loading branch information
samtgarson committed Apr 12, 2024
1 parent d91dee9 commit ef89e37
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
8 changes: 6 additions & 2 deletions web/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { inngest } from '@books-about-food/core/jobs'
import prisma from '@books-about-food/database'
import NextAuth from 'next-auth'
import { identify } from './lib/tracking/identify'
import { track } from './lib/tracking/track'
import { authConfig } from './utils/auth-config'

export const {
Expand Down Expand Up @@ -80,8 +81,11 @@ export const {
}
},
events: {
async signIn({ user }) {
await identify(user)
async signIn({ user, isNewUser }) {
await Promise.all([
identify(user),
track(user.id as string, 'Signed In', { 'First Time': !!isNewUser })
])
}
}
})
20 changes: 17 additions & 3 deletions web/src/lib/tracking/track.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ import { token, trackingEnabled } from './utils'
type CommonEventProperties = {
$browser?: string
$device?: string
$device_id?: string
$os?: string
$referrer?: string | null
ip?: string | null
}

const BAF_SESSION_ID = 'baf-session-id'

export async function track<T extends keyof TrackableEvents>(
userId: string | undefined,
event: T,
Expand All @@ -26,9 +29,7 @@ export async function track<T extends keyof TrackableEvents>(
if (!token) return

const distinct_id =
userId ||
req?.cookies.get('baf-session-id')?.value ||
generateAnonymousId(res?.cookies)
userId || getSessionId(req) || generateAnonymousId(res?.cookies)

const body = {
event,
Expand All @@ -45,6 +46,8 @@ export async function track<T extends keyof TrackableEvents>(
body: JSON.stringify([body]),
headers: { 'content-type': 'application/json', accept: 'text/plain' }
})

if (userId && distinct_id !== userId) clearSessionId(req)
}

function getCommonProperties(req?: NextRequest): CommonEventProperties {
Expand All @@ -57,6 +60,7 @@ function getCommonProperties(req?: NextRequest): CommonEventProperties {
$device: ua.device.type,
$os: ua.os.name,
$referrer: h.get('referer'),
$device_id: getSessionId(req),
ip:
h.get('cf-connecting-ip') ||
req?.ip ||
Expand All @@ -79,3 +83,13 @@ function generateAnonymousId(c: ResponseCookies = cookies()) {
})
return anonId
}

function getSessionId(req?: NextRequest) {
if (req) return req?.cookies.get(BAF_SESSION_ID)?.value
return cookies().get(BAF_SESSION_ID)?.value
}

function clearSessionId(req?: NextRequest) {
if (req) return req?.cookies.delete(BAF_SESSION_ID)
return cookies().delete(BAF_SESSION_ID)
}

0 comments on commit ef89e37

Please sign in to comment.