π 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
feat: Profile identification
Blue Mouse71d77e520cea
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.tsindex c43ee7eb0..928f15a9b 100644--- a/backend/apps/cloud/src/analytics/analytics.controller.ts+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts@@ -111,6 +111,7 @@ import { GetKeywordsDto } from './dto/get-keywords.dto'import { GetBotStatsDto } from './dto/get-bot-stats.dto'import { GSC_ALL_TIME_DAYS, GSCService } from '../project/gsc.service'import { GetProfileIdDto, GetSessionIdDto } from './dto/get-id.dto'+import { IdentifyDto } from './dto/identify.dto'import { ExperimentService } from '../experiment/experiment.service'import {ExperimentStatus,@@ -3297,6 +3298,74 @@ export class AnalyticsController {return { ...result, appliedFilters, timeBucket: timeBucketForAllTime }}+ /**+ * Links the visitor's current anonymous profile to an identified profile+ * derived from the user ID supplied by the site (e.g. after log in). Events+ * previously recorded for the anonymous profile get attributed to the+ * identified profile at query time; the tracker stamps all subsequent+ * events with the supplied profileId directly.+ */+ @Post('identify')+ @Public()+ async identify(+ @Body() dto: IdentifyDto,+ @Headers() headers,+ @Ip() reqIP,+ ): Promise<{ profileId: string }> {+ const { 'user-agent': userAgent, origin } = headers+ const ip = getIPFromHeaders(headers) || reqIP || ''++ this.analyticsService.validateUserSuppliedProfileId(dto.profileId)++ await this.analyticsService.validate(dto, origin, ip)++ const userProfileId = await this.analyticsService.generateProfileId(+ dto.pid,+ userAgent,+ ip,+ dto.profileId,+ )++ const anonProfileId = await this.analyticsService.generateProfileId(+ dto.pid,+ userAgent,+ ip,+ )++ const linked = await this.analyticsService.linkProfiles(+ dto.pid,+ anonProfileId,+ userProfileId,+ )++ // Flip the visitor's current session (if any) to the identified profile.+ // Skipped when the anonymous profile is already linked to a different+ // identified profile (e.g. a second account on a shared device) - the+ // session stays with the current identity until new events re-stamp it.+ if (linked) {+ const { exists, psid } = await this.analyticsService.getSessionId(+ dto.pid,+ userAgent,+ ip,+ )++ if (exists) {+ await this.analyticsService.recordSessionActivity(+ psid,+ dto.pid,+ userProfileId,+ )+ }+ }++ this.logger.log(+ `pid: ${dto.pid}, profileId: ${userProfileId}`,+ 'POST /analytics/identify',+ )++ return { profileId: userProfileId }+ }+// Revenue attribution endpoints@Post('profile-id')diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 08cde15b7..b6a7913e1 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -2417,6 +2417,204 @@ export class AnalyticsService {return profileId.startsWith(AnalyticsService.PROFILE_PREFIX_USER)}+ // Values that are almost certainly instrumentation bugs rather than real user+ // IDs (e.g. stringified nulls). Identifying with them would fuse unrelated+ // visitors into a single profile.+ private static readonly ILLEGAL_USER_PROFILE_IDS = new Set([+ '',+ 'null',+ 'undefined',+ 'nan',+ 'none',+ 'nil',+ 'true',+ 'false',+ '0',+ 'anonymous',+ 'anon',+ 'guest',+ 'user',+ 'id',+ 'distinct_id',+ 'distinctid',+ 'profileid',+ 'profile_id',+ 'not_authenticated',+ 'email',+ '[object object]',+ ])++ validateUserSuppliedProfileId(userSupplied: string): void {+ const normalised = userSupplied.trim().toLowerCase()++ if (AnalyticsService.ILLEGAL_USER_PROFILE_IDS.has(normalised)) {+ throw new BadRequestException(+ `"${userSupplied}" is not a valid profileId. Pass a unique, stable identifier of the user (e.g. an internal user ID), see https://docs.swetrix.com/visitor-identification`,+ )+ }+ }++ private getProfileAliasKey(pid: string, anonProfileId: string): string {+ return `pfa:${pid}:${anonProfileId}`+ }++ /**+ * Looks up the identified (usr_) profile an anonymous (anon_) profile has+ * been linked to. First identification wins, so the mapping is resolved+ * with argMin(created).+ */+ async getUserProfileForAnon(+ pid: string,+ anonProfileId: string,+ ): Promise<string | null> {+ const cacheKey = this.getProfileAliasKey(pid, anonProfileId)++ const cached = await redis.get(cacheKey)++ if (cached) {+ return cached+ }++ const query = `+ SELECT argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ AND anonProfileId = {anonProfileId:String}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: { pid, anonProfileId },+ })+ .then((resultSet) => resultSet.json<{ userProfileId: string | null }>())++ const userProfileId = data[0]?.userProfileId || null++ if (userProfileId) {+ await redis.set(cacheKey, userProfileId, 'EX', 3600)+ }++ return userProfileId+ }++ /**+ * Links an anonymous (anon_) profile to an identified (usr_) profile.+ * The link is created only once per anonymous profile - if it is already+ * linked to a different user, the existing link is kept (first+ * identification wins; e.g. a second person logging in on a shared device+ * must not steal the anonymous history of the first).+ *+ * @returns whether the anonymous profile is linked to the supplied user+ * profile after the call+ */+ async linkProfiles(+ pid: string,+ anonProfileId: string,+ userProfileId: string,+ ): Promise<boolean> {+ const existing = await this.getUserProfileForAnon(pid, anonProfileId)++ if (existing) {+ return existing === userProfileId+ }++ try {+ await clickhouse.insert({+ table: 'profile_aliases',+ format: 'JSONEachRow',+ values: [+ {+ pid,+ anonProfileId,+ userProfileId,+ created: dayjs.utc().format('YYYY-MM-DD HH:mm:ss'),+ },+ ],+ clickhouse_settings: { async_insert: 1 },+ })++ await redis.set(+ this.getProfileAliasKey(pid, anonProfileId),+ userProfileId,+ 'EX',+ 3600,+ )+ } catch (error) {+ this.logger.error(`[linkProfiles] Failed to link profiles: ${error}`)+ return false+ }++ return true+ }++ /**+ * Resolves the full identity of a profile: the canonical profile ID to+ * display and every profile ID whose events belong to it.+ *+ * For an identified (usr_) profile this is the profile itself plus all+ * anonymous profiles linked to it. For a linked anonymous profile the+ * identity is canonicalised to the identified profile. For an unlinked+ * anonymous profile it is just the profile itself.+ */+ async resolveProfileIdentity(+ pid: string,+ profileId: string,+ ): Promise<{ canonicalId: string; profileIds: string[] }> {+ if (!this.isUserSuppliedProfile(profileId)) {+ const userProfileId = await this.getUserProfileForAnon(pid, profileId)++ if (!userProfileId) {+ return { canonicalId: profileId, profileIds: [profileId] }+ }++ profileId = userProfileId+ }++ const query = `+ SELECT anonProfileId+ FROM (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ )+ WHERE userProfileId = {userProfileId:String}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: { pid, userProfileId: profileId },+ })+ .then((resultSet) => resultSet.json<{ anonProfileId: string }>())++ return {+ canonicalId: profileId,+ profileIds: [profileId, ..._map(data, 'anonProfileId')],+ }+ }++ /**+ * CTE mapping anonymous profile IDs to the identified profiles they are+ * linked to. LEFT JOIN it on profileId and coalesce(nullIf(pam.userProfileId, ''),+ * profileId) to attribute pre-identification events to the identified+ * profile. Requires a {pid:FixedString(12)} query param.+ */+ private buildProfileAliasMapCTE(): string {+ return `+ profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ )`+ }+private getSessionFirstSeenKey(pid: string, psid: string): string {return `ses:fs:${pid}:${psid}`}@@ -3651,7 +3849,15 @@ export class AnalyticsService {)const query = `- WITH funnel_qualified AS (+ WITH profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ ),+ funnel_qualified AS (SELECT psidFROM (SELECT@@ -3728,20 +3934,22 @@ export class AnalyticsService {CAST(psid, 'String') AS psidCasted,pid,dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,- argMax(profileId, lastSeen) as profileId- FROM sessions+ argMax(coalesce(nullIf(pam.userProfileId, ''), s.profileId), lastSeen) as profileId+ FROM sessions AS s+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}AND psid IN (SELECT psid FROM funnel_qualified)GROUP BY psidCasted, pid),first_session_per_profile AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), s.profileId) AS profileId,argMin(CAST(psid, 'String'), firstSeen) AS firstPsid- FROM sessions FINAL+ FROM sessions AS s FINAL+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}- AND profileId IS NOT NULL- AND profileId != ''+ AND s.profileId IS NOT NULL+ AND s.profileId != ''GROUP BY profileId)SELECT@@ -3810,7 +4018,15 @@ export class AnalyticsService {: ''const query = `- WITH journey_qualified AS (+ WITH profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ ),+ journey_qualified AS (SELECT psidFROM (SELECT@@ -3883,20 +4099,22 @@ export class AnalyticsService {CAST(psid, 'String') AS psidCasted,pid,dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,- argMax(profileId, lastSeen) as profileId- FROM sessions+ argMax(coalesce(nullIf(pam.userProfileId, ''), s.profileId), lastSeen) as profileId+ FROM sessions AS s+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}AND psid IN (SELECT psid FROM journey_qualified)GROUP BY psidCasted, pid),first_session_per_profile AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), s.profileId) AS profileId,argMin(CAST(psid, 'String'), firstSeen) AS firstPsid- FROM sessions FINAL+ FROM sessions AS s FINAL+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}- AND profileId IS NOT NULL- AND profileId != ''+ AND s.profileId IS NOT NULL+ AND s.profileId != ''GROUP BY profileId)SELECT@@ -7650,6 +7868,19 @@ export class AnalyticsService {const replay = await this.getSessionReplaySummary(pid, psid)+ // If the session's profile was linked to an identified profile+ // (via the identify API), display the identified profile+ if (details?.profileId && !this.isUserSuppliedProfile(details.profileId)) {+ const userProfileId = await this.getUserProfileForAnon(+ pid,+ details.profileId,+ )++ if (userProfileId) {+ details.profileId = userProfileId+ }+ }+return {pages: this.processPageflow(pages),details: {@@ -7684,7 +7915,15 @@ export class AnalyticsService {)const query = `- WITH distinct_sessions_filtered AS (+ WITH profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ ),+ distinct_sessions_filtered AS (SELECTpsidCasted,pid,@@ -7757,8 +7996,9 @@ export class AnalyticsService {toString(psid) AS psidCasted,pid,dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,- argMax(profileId, lastSeen) as profileId- FROM sessions+ argMax(coalesce(nullIf(pam.userProfileId, ''), s.profileId), lastSeen) as profileId+ FROM sessions AS s+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}GROUP BY psidCasted, pid),@@ -7778,12 +8018,13 @@ export class AnalyticsService {),first_session_per_profile AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), s.profileId) AS profileId,argMin(toString(psid), firstSeen) AS firstPsid- FROM sessions FINAL+ FROM sessions AS s FINAL+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}- AND profileId IS NOT NULL- AND profileId != ''+ AND s.profileId IS NOT NULL+ AND s.profileId != ''GROUP BY profileId),sessions_enriched AS (@@ -7930,7 +8171,15 @@ export class AnalyticsService {)`const query = `- WITH ${filteredSessionsCTE},+ WITH profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ ),+ ${filteredSessionsCTE},replay_summary AS (SELECTpsidCasted,@@ -8025,8 +8274,9 @@ export class AnalyticsService {toString(psid) AS psidCasted,pid,dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,- argMax(profileId, lastSeen) as profileId- FROM sessions+ argMax(coalesce(nullIf(pam.userProfileId, ''), s.profileId), lastSeen) as profileId+ FROM sessions AS s+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}GROUP BY psidCasted, pid),@@ -8065,12 +8315,13 @@ export class AnalyticsService {),first_session_per_profile AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), s.profileId) AS profileId,argMin(toString(psid), firstSeen) AS firstPsid- FROM sessions FINAL+ FROM sessions AS s FINAL+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}- AND profileId IS NOT NULL- AND profileId != ''+ AND s.profileId IS NOT NULL+ AND s.profileId != ''GROUP BY profileId)SELECT@@ -8308,12 +8559,11 @@ export class AnalyticsService {private buildProfilesListDataCTE(filtersQuery: string,- profileTypeFilter: string,customEVFilterApplied: boolean,): string {const scopedProfileFilter = customEVFilterApplied? `- AND profileId IN (+ AND events.profileId IN (SELECT DISTINCT profileIdFROM eventsWHERE pid = {pid:FixedString(12)}@@ -8321,16 +8571,17 @@ export class AnalyticsService {AND created BETWEEN {groupFrom:String} AND {groupTo:String}AND profileId IS NOT NULLAND profileId != ''- ${profileTypeFilter}${filtersQuery})`: filtersQuery+ // Events recorded for an anonymous profile before the visitor was+ // identified get attributed to the identified profile via profile_alias_mapreturn `all_profile_data AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), events.profileId) AS profileId,psid,cc,os,@@ -8341,12 +8592,12 @@ export class AnalyticsService {if(type = 'custom_event', 1, 0) AS isEvent,if(type = 'error', 1, 0) AS isErrorFROM events+ LEFT JOIN profile_alias_map pam ON events.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event', 'error')AND created BETWEEN {groupFrom:String} AND {groupTo:String}- AND profileId IS NOT NULL- AND profileId != ''- ${profileTypeFilter}+ AND events.profileId IS NOT NULL+ AND events.profileId != ''${scopedProfileFilter})`}@@ -8361,21 +8612,23 @@ export class AnalyticsService {profileType: 'all' | 'anonymous' | 'identified' = 'all',customEVFilterApplied = false,): Promise<object[]> {+ // The profile type filter is applied to the alias-resolved profileId, so+ // anonymous history linked to an identified profile counts as identifiedlet profileTypeFilter = ''if (profileType === 'anonymous') {- profileTypeFilter = `AND profileId LIKE '${AnalyticsService.PROFILE_PREFIX_ANON}%'`+ profileTypeFilter = `WHERE profileId LIKE '${AnalyticsService.PROFILE_PREFIX_ANON}%'`} else if (profileType === 'identified') {- profileTypeFilter = `AND profileId LIKE '${AnalyticsService.PROFILE_PREFIX_USER}%'`+ profileTypeFilter = `WHERE profileId LIKE '${AnalyticsService.PROFILE_PREFIX_USER}%'`}const allProfileDataCTE = this.buildProfilesListDataCTE(filtersQuery,- profileTypeFilter,customEVFilterApplied,)const query = `- WITH ${allProfileDataCTE},+ WITH ${this.buildProfileAliasMapCTE()},+ ${allProfileDataCTE},profile_aggregated AS (SELECTprofileId,@@ -8390,6 +8643,7 @@ export class AnalyticsService {any(br) AS br_agg,any(dv) AS dv_aggFROM all_profile_data+ ${profileTypeFilter}GROUP BY profileId)SELECT@@ -8430,6 +8684,11 @@ export class AnalyticsService {profileId: string,_safeTimezone: string,): Promise<any> {+ const { canonicalId, profileIds } = await this.resolveProfileIdentity(+ pid,+ profileId,+ )+// Query session count from sessions tableconst querySessionCount = `SELECT@@ -8438,7 +8697,7 @@ export class AnalyticsService {max(sessions.lastSeen) AS lastSeenFROM sessions FINALWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`// Prefer pageview timings, but fall back to sessions for event/error-only profiles.@@ -8453,7 +8712,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLGROUP BY psidHAVING session_duration > 0@@ -8468,7 +8727,7 @@ export class AnalyticsService {dateDiff('second', min(firstSeen), max(lastSeen)) AS session_durationFROM sessions FINALWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}GROUP BY psidHAVING session_duration > 0)@@ -8483,7 +8742,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`const queryEvents = `@@ -8491,7 +8750,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'custom_event'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`const queryErrors = `@@ -8499,7 +8758,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'error'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`const queryDetails = `@@ -8515,7 +8774,7 @@ export class AnalyticsService {any(lc) AS lcFROM eventsWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND type IN ('pageview', 'custom_event', 'error')`@@ -8529,14 +8788,14 @@ export class AnalyticsService {argMax(currency, synced_at) AS currencyFROM revenueWHERE pid = {pid:FixedString(12)}- AND profile_id = {profileId:String}+ AND profile_id IN {profileIds:Array(String)}AND type IN ('sale', 'subscription')AND status = 'completed'GROUP BY transaction_id)`- const params = { pid, profileId }+ const params = { pid, profileIds }const [sessionCountResult,@@ -8582,8 +8841,8 @@ export class AnalyticsService {const revenue = (revenueResult.data[0] || {}) as Record<string, any>return {- profileId,- isIdentified: this.isUserSuppliedProfile(profileId),+ profileId: canonicalId,+ isIdentified: this.isUserSuppliedProfile(canonicalId),sessionsCount: sessionCount.sessionsCount || 0,pageviewsCount: pageviews.pageviewsCount || 0,eventsCount: events.eventsCount || 0,@@ -8602,6 +8861,8 @@ export class AnalyticsService {profileId: string,limit = 10,): Promise<{ page: string; count: number }[]> {+ const { profileIds } = await this.resolveProfileIdentity(pid, profileId)+const query = `SELECTpg AS page,@@ -8609,7 +8870,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}GROUP BY pgORDER BY count DESCLIMIT {limit:UInt32}@@ -8618,7 +8879,7 @@ export class AnalyticsService {const { data } = await clickhouse.query({query,- query_params: { pid, profileId, limit: Number(limit) },+ query_params: { pid, profileIds, limit: Number(limit) },}).then((resultSet) => resultSet.json())@@ -8630,6 +8891,8 @@ export class AnalyticsService {profileId: string,months = 4,): Promise<{ date: string; pageviews: number; events: number }[]> {+ const { profileIds } = await this.resolveProfileIdentity(pid, profileId)+const startDate = dayjs.utc().subtract(months, 'month')@@ -8644,7 +8907,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event')- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND created >= {startDate:Date}GROUP BY dateORDER BY date ASC@@ -8653,7 +8916,7 @@ export class AnalyticsService {const { data } = await clickhouse.query({query,- query_params: { pid, profileId, startDate },+ query_params: { pid, profileIds, startDate },}).then((resultSet) => resultSet.json())@@ -8671,7 +8934,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'custom_event'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}${filtersQuery}@@ -8684,7 +8947,6 @@ export class AnalyticsService {SELECTCAST(psid, 'String') AS psidCasted,pid,- profileId,cc,os,br,@@ -8692,7 +8954,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event', 'error')- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}${scopedSessionFilter}@@ -8703,7 +8965,7 @@ export class AnalyticsService {pid: string,psids: string[],safeTimezone: string,- profileId: string,+ profileIds: string[],groupFrom: string,groupTo: string,): Promise<Map<string, any[]>> {@@ -8750,7 +9012,7 @@ export class AnalyticsService {WHEREpid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event', 'error')- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND toString(psid) IN {psids:Array(String)}AND created BETWEEN {groupFrom:String} AND {groupTo:String}@@ -8795,7 +9057,7 @@ export class AnalyticsService {FROM revenueWHEREpid = {pid:FixedString(12)}- AND profile_id = {profileId:String}+ AND profile_id IN {profileIds:Array(String)}AND session_id IS NOT NULLAND toString(session_id) IN {psids:Array(String)}AND revenue.created BETWEEN {groupFrom:String} AND {groupTo:String}@@ -8821,7 +9083,7 @@ export class AnalyticsService {pid,psids,timezone: safeTimezone,- profileId,+ profileIds,groupFrom,groupTo,},@@ -8856,6 +9118,8 @@ export class AnalyticsService {skip = 0,customEVFilterApplied = false,): Promise<object[]> {+ const { profileIds } = await this.resolveProfileIdentity(pid, profileId)+const allProfileEventsCTE = this.buildProfileSessionsEventsCTE(filtersQuery,customEVFilterApplied,@@ -8867,14 +9131,13 @@ export class AnalyticsService {SELECTpsidCasted,pid,- profileId,any(cc) AS cc_agg,any(os) AS os_agg,any(br) AS br_agg,min(created_tz) AS sessionStart,max(created_tz) AS lastActivityFROM all_profile_events- GROUP BY psidCasted, pid, profileId+ GROUP BY psidCasted, pid),pageview_counts AS (SELECT@@ -8884,7 +9147,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}GROUP BY psidCasted, pid@@ -8897,7 +9160,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'custom_event'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}GROUP BY psidCasted, pid@@ -8910,7 +9173,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'error'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}GROUP BY psidCasted, pid@@ -8922,7 +9185,7 @@ export class AnalyticsService {dateDiff('second', min(firstSeen), max(lastSeen)) as avg_durationFROM sessionsWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}GROUP BY psidCasted, pid)SELECT@@ -8953,7 +9216,7 @@ export class AnalyticsService {query,query_params: {pid,- profileId,+ profileIds,...paramsData.params,timezone: safeTimezone,take,@@ -8967,7 +9230,7 @@ export class AnalyticsService {pid,sessions.map((session) => String(session.psid)).filter(Boolean),safeTimezone,- profileId,+ profileIds,paramsData.params.groupFrom,paramsData.params.groupTo,)diff --git a/backend/apps/cloud/src/analytics/dto/identify.dto.ts b/backend/apps/cloud/src/analytics/dto/identify.dto.tsnew file mode 100644index 000000000..570174679--- /dev/null+++ b/backend/apps/cloud/src/analytics/dto/identify.dto.ts@@ -0,0 +1,25 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsString, Matches, MaxLength } from 'class-validator'+import { PID_REGEX } from '../../common/constants'++export class IdentifyDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({+ example: 'user_12345',+ required: true,+ description:+ 'A unique, stable identifier of the user (e.g. an internal user ID). It is hashed before storage; the raw value is never persisted. The current anonymous profile of the visitor gets linked to the resulting identified profile.',+ })+ @IsNotEmpty()+ @IsString()+ @MaxLength(256)+ profileId: string+}diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.tsindex 62ef26360..a84596c3a 100644--- a/backend/apps/community/src/analytics/analytics.controller.ts+++ b/backend/apps/community/src/analytics/analytics.controller.ts@@ -63,6 +63,7 @@ import { GetSessionDto } from './dto/get-session.dto'import { GetProfilesDto } from './dto/get-profiles.dto'import { GetProfileDto, GetProfileSessionsDto } from './dto/get-profile.dto'import { GetProfileIdDto, GetSessionIdDto } from './dto/get-id.dto'+import { IdentifyDto } from './dto/identify.dto'import { ErrorDto } from './dto/error.dto'import { GetErrorsDto } from './dto/get-errors.dto'import { GetErrorDto } from './dto/get-error.dto'@@ -2788,6 +2789,74 @@ export class AnalyticsController {return { sessions, appliedFilters, take, skip }}+ /**+ * Links the visitor's current anonymous profile to an identified profile+ * derived from the user ID supplied by the site (e.g. after log in). Events+ * previously recorded for the anonymous profile get attributed to the+ * identified profile at query time; the tracker stamps all subsequent+ * events with the supplied profileId directly.+ */+ @Post('identify')+ @Public()+ async identify(+ @Body() dto: IdentifyDto,+ @Headers() headers,+ @Ip() reqIP,+ ): Promise<{ profileId: string }> {+ const { 'user-agent': userAgent, origin } = headers+ const ip = getIPFromHeaders(headers) || reqIP || ''++ this.analyticsService.validateUserSuppliedProfileId(dto.profileId)++ await this.analyticsService.validate(dto, origin, ip)++ const userProfileId = await this.analyticsService.generateProfileId(+ dto.pid,+ userAgent,+ ip,+ dto.profileId,+ )++ const anonProfileId = await this.analyticsService.generateProfileId(+ dto.pid,+ userAgent,+ ip,+ )++ const linked = await this.analyticsService.linkProfiles(+ dto.pid,+ anonProfileId,+ userProfileId,+ )++ // Flip the visitor's current session (if any) to the identified profile.+ // Skipped when the anonymous profile is already linked to a different+ // identified profile (e.g. a second account on a shared device) - the+ // session stays with the current identity until new events re-stamp it.+ if (linked) {+ const { exists, psid } = await this.analyticsService.getSessionId(+ dto.pid,+ userAgent,+ ip,+ )++ if (exists) {+ await this.analyticsService.recordSessionActivity(+ psid,+ dto.pid,+ userProfileId,+ )+ }+ }++ this.logger.log(+ `pid: ${dto.pid}, profileId: ${userProfileId}`,+ 'POST /analytics/identify',+ )++ return { profileId: userProfileId }+ }+@Post('profile-id')@Public()async getOrCreateProfileId(diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex c00dd5dfc..2c4fdfc7c 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -690,7 +690,11 @@ export class AnalyticsService {}async validate(- logDTO: PageviewsDto | EventsDto | ErrorDto,+ logDTO:+ | PageviewsDto+ | EventsDto+ | ErrorDto+ | { pid: string; lc?: string | null },origin: string,ip?: string,): Promise<Project> {@@ -2054,6 +2058,204 @@ export class AnalyticsService {return profileId.startsWith(AnalyticsService.PROFILE_PREFIX_USER)}+ // Values that are almost certainly instrumentation bugs rather than real user+ // IDs (e.g. stringified nulls). Identifying with them would fuse unrelated+ // visitors into a single profile.+ private static readonly ILLEGAL_USER_PROFILE_IDS = new Set([+ '',+ 'null',+ 'undefined',+ 'nan',+ 'none',+ 'nil',+ 'true',+ 'false',+ '0',+ 'anonymous',+ 'anon',+ 'guest',+ 'user',+ 'id',+ 'distinct_id',+ 'distinctid',+ 'profileid',+ 'profile_id',+ 'not_authenticated',+ 'email',+ '[object object]',+ ])++ validateUserSuppliedProfileId(userSupplied: string): void {+ const normalised = userSupplied.trim().toLowerCase()++ if (AnalyticsService.ILLEGAL_USER_PROFILE_IDS.has(normalised)) {+ throw new BadRequestException(+ `"${userSupplied}" is not a valid profileId. Pass a unique, stable identifier of the user (e.g. an internal user ID), see https://docs.swetrix.com/visitor-identification`,+ )+ }+ }++ private getProfileAliasKey(pid: string, anonProfileId: string): string {+ return `pfa:${pid}:${anonProfileId}`+ }++ /**+ * Looks up the identified (usr_) profile an anonymous (anon_) profile has+ * been linked to. First identification wins, so the mapping is resolved+ * with argMin(created).+ */+ async getUserProfileForAnon(+ pid: string,+ anonProfileId: string,+ ): Promise<string | null> {+ const cacheKey = this.getProfileAliasKey(pid, anonProfileId)++ const cached = await redis.get(cacheKey)++ if (cached) {+ return cached+ }++ const query = `+ SELECT argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ AND anonProfileId = {anonProfileId:String}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: { pid, anonProfileId },+ })+ .then((resultSet) => resultSet.json<{ userProfileId: string | null }>())++ const userProfileId = data[0]?.userProfileId || null++ if (userProfileId) {+ await redis.set(cacheKey, userProfileId, 'EX', 3600)+ }++ return userProfileId+ }++ /**+ * Links an anonymous (anon_) profile to an identified (usr_) profile.+ * The link is created only once per anonymous profile - if it is already+ * linked to a different user, the existing link is kept (first+ * identification wins; e.g. a second person logging in on a shared device+ * must not steal the anonymous history of the first).+ *+ * @returns whether the anonymous profile is linked to the supplied user+ * profile after the call+ */+ async linkProfiles(+ pid: string,+ anonProfileId: string,+ userProfileId: string,+ ): Promise<boolean> {+ const existing = await this.getUserProfileForAnon(pid, anonProfileId)++ if (existing) {+ return existing === userProfileId+ }++ try {+ await clickhouse.insert({+ table: 'profile_aliases',+ format: 'JSONEachRow',+ values: [+ {+ pid,+ anonProfileId,+ userProfileId,+ created: dayjs.utc().format('YYYY-MM-DD HH:mm:ss'),+ },+ ],+ clickhouse_settings: { async_insert: 1 },+ })++ await redis.set(+ this.getProfileAliasKey(pid, anonProfileId),+ userProfileId,+ 'EX',+ 3600,+ )+ } catch (error) {+ this.logger.error(`[linkProfiles] Failed to link profiles: ${error}`)+ return false+ }++ return true+ }++ /**+ * Resolves the full identity of a profile: the canonical profile ID to+ * display and every profile ID whose events belong to it.+ *+ * For an identified (usr_) profile this is the profile itself plus all+ * anonymous profiles linked to it. For a linked anonymous profile the+ * identity is canonicalised to the identified profile. For an unlinked+ * anonymous profile it is just the profile itself.+ */+ async resolveProfileIdentity(+ pid: string,+ profileId: string,+ ): Promise<{ canonicalId: string; profileIds: string[] }> {+ if (!this.isUserSuppliedProfile(profileId)) {+ const userProfileId = await this.getUserProfileForAnon(pid, profileId)++ if (!userProfileId) {+ return { canonicalId: profileId, profileIds: [profileId] }+ }++ profileId = userProfileId+ }++ const query = `+ SELECT anonProfileId+ FROM (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ )+ WHERE userProfileId = {userProfileId:String}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: { pid, userProfileId: profileId },+ })+ .then((resultSet) => resultSet.json<{ anonProfileId: string }>())++ return {+ canonicalId: profileId,+ profileIds: [profileId, ..._map(data, 'anonProfileId')],+ }+ }++ /**+ * CTE mapping anonymous profile IDs to the identified profiles they are+ * linked to. LEFT JOIN it on profileId and coalesce(nullIf(pam.userProfileId, ''),+ * profileId) to attribute pre-identification events to the identified+ * profile. Requires a {pid:FixedString(12)} query param.+ */+ private buildProfileAliasMapCTE(): string {+ return `+ profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ )`+ }+private getSessionFirstSeenKey(pid: string, psid: string): string {return `ses:fs:${pid}:${psid}`}@@ -2472,7 +2674,15 @@ export class AnalyticsService {)const query = `- WITH funnel_qualified AS (+ WITH profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ ),+ funnel_qualified AS (SELECT psidFROM (SELECT@@ -2549,20 +2759,22 @@ export class AnalyticsService {CAST(psid, 'String') AS psidCasted,pid,dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,- argMax(profileId, lastSeen) as profileId- FROM sessions+ argMax(coalesce(nullIf(pam.userProfileId, ''), s.profileId), lastSeen) as profileId+ FROM sessions AS s+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}AND psid IN (SELECT psid FROM funnel_qualified)GROUP BY psidCasted, pid),first_session_per_profile AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), s.profileId) AS profileId,argMin(CAST(psid, 'String'), firstSeen) AS firstPsid- FROM sessions FINAL+ FROM sessions AS s FINAL+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}- AND profileId IS NOT NULL- AND profileId != ''+ AND s.profileId IS NOT NULL+ AND s.profileId != ''GROUP BY profileId)SELECT@@ -2631,7 +2843,15 @@ export class AnalyticsService {: ''const query = `- WITH journey_qualified AS (+ WITH profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ ),+ journey_qualified AS (SELECT psidFROM (SELECT@@ -2704,20 +2924,22 @@ export class AnalyticsService {CAST(psid, 'String') AS psidCasted,pid,dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,- argMax(profileId, lastSeen) as profileId- FROM sessions+ argMax(coalesce(nullIf(pam.userProfileId, ''), s.profileId), lastSeen) as profileId+ FROM sessions AS s+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}AND psid IN (SELECT psid FROM journey_qualified)GROUP BY psidCasted, pid),first_session_per_profile AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), s.profileId) AS profileId,argMin(CAST(psid, 'String'), firstSeen) AS firstPsid- FROM sessions FINAL+ FROM sessions AS s FINAL+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}- AND profileId IS NOT NULL- AND profileId != ''+ AND s.profileId IS NOT NULL+ AND s.profileId != ''GROUP BY profileId)SELECT@@ -6092,6 +6314,19 @@ export class AnalyticsService {isLive = lastActivityTime.isAfter(liveThresholdTime)}+ // If the session's profile was linked to an identified profile+ // (via the identify API), display the identified profile+ if (details?.profileId && !this.isUserSuppliedProfile(details.profileId)) {+ const userProfileId = await this.getUserProfileForAnon(+ pid,+ details.profileId,+ )++ if (userProfileId) {+ details.profileId = userProfileId+ }+ }+return {pages: this.processPageflow(pages),details: {@@ -6123,7 +6358,15 @@ export class AnalyticsService {)const query = `- WITH distinct_sessions_filtered AS (+ WITH profile_alias_map AS (+ SELECT+ anonProfileId,+ argMin(userProfileId, created) AS userProfileId+ FROM profile_aliases+ WHERE pid = {pid:FixedString(12)}+ GROUP BY anonProfileId+ ),+ distinct_sessions_filtered AS (SELECTpsidCasted,pid,@@ -6171,19 +6414,21 @@ export class AnalyticsService {CAST(psid, 'String') AS psidCasted,pid,dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,- argMax(profileId, lastSeen) as profileId- FROM sessions+ argMax(coalesce(nullIf(pam.userProfileId, ''), s.profileId), lastSeen) as profileId+ FROM sessions AS s+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}GROUP BY psidCasted, pid),first_session_per_profile AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), s.profileId) AS profileId,argMin(CAST(psid, 'String'), firstSeen) AS firstPsid- FROM sessions FINAL+ FROM sessions AS s FINAL+ LEFT JOIN profile_alias_map pam ON s.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}- AND profileId IS NOT NULL- AND profileId != ''+ AND s.profileId IS NOT NULL+ AND s.profileId != ''GROUP BY profileId),sessions_enriched AS (@@ -7136,12 +7381,11 @@ export class AnalyticsService {private buildProfilesListDataCTE(filtersQuery: string,- profileTypeFilter: string,customEVFilterApplied: boolean,): string {const scopedProfileFilter = customEVFilterApplied? `- AND profileId IN (+ AND events.profileId IN (SELECT DISTINCT profileIdFROM eventsWHERE pid = {pid:FixedString(12)}@@ -7149,16 +7393,17 @@ export class AnalyticsService {AND created BETWEEN {groupFrom:String} AND {groupTo:String}AND profileId IS NOT NULLAND profileId != ''- ${profileTypeFilter}${filtersQuery})`: filtersQuery+ // Events recorded for an anonymous profile before the visitor was+ // identified get attributed to the identified profile via profile_alias_mapreturn `all_profile_data AS (SELECT- profileId,+ coalesce(nullIf(pam.userProfileId, ''), events.profileId) AS profileId,psid,cc,os,@@ -7169,12 +7414,12 @@ export class AnalyticsService {if(type = 'custom_event', 1, 0) AS isEvent,if(type = 'error', 1, 0) AS isErrorFROM events+ LEFT JOIN profile_alias_map pam ON events.profileId = pam.anonProfileIdWHERE pid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event', 'error')AND created BETWEEN {groupFrom:String} AND {groupTo:String}- AND profileId IS NOT NULL- AND profileId != ''- ${profileTypeFilter}+ AND events.profileId IS NOT NULL+ AND events.profileId != ''${scopedProfileFilter})`}@@ -7189,21 +7434,23 @@ export class AnalyticsService {profileType: 'all' | 'anonymous' | 'identified' = 'all',customEVFilterApplied = false,): Promise<object[]> {+ // The profile type filter is applied to the alias-resolved profileId, so+ // anonymous history linked to an identified profile counts as identifiedlet profileTypeFilter = ''if (profileType === 'anonymous') {- profileTypeFilter = `AND profileId LIKE '${AnalyticsService.PROFILE_PREFIX_ANON}%'`+ profileTypeFilter = `WHERE profileId LIKE '${AnalyticsService.PROFILE_PREFIX_ANON}%'`} else if (profileType === 'identified') {- profileTypeFilter = `AND profileId LIKE '${AnalyticsService.PROFILE_PREFIX_USER}%'`+ profileTypeFilter = `WHERE profileId LIKE '${AnalyticsService.PROFILE_PREFIX_USER}%'`}const allProfileDataCTE = this.buildProfilesListDataCTE(filtersQuery,- profileTypeFilter,customEVFilterApplied,)const query = `- WITH ${allProfileDataCTE},+ WITH ${this.buildProfileAliasMapCTE()},+ ${allProfileDataCTE},profile_aggregated AS (SELECTprofileId,@@ -7218,6 +7465,7 @@ export class AnalyticsService {any(br) AS br_agg,any(dv) AS dv_aggFROM all_profile_data+ ${profileTypeFilter}GROUP BY profileId)SELECT@@ -7258,6 +7506,11 @@ export class AnalyticsService {profileId: string,_safeTimezone: string,): Promise<any> {+ const { canonicalId, profileIds } = await this.resolveProfileIdentity(+ pid,+ profileId,+ )+// Query session count from sessions tableconst querySessionCount = `SELECT@@ -7266,7 +7519,7 @@ export class AnalyticsService {max(sessions.lastSeen) AS lastSeenFROM sessions FINALWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`// Prefer pageview timings, but fall back to sessions for event/error-only profiles.@@ -7281,7 +7534,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLGROUP BY psidHAVING session_duration > 0@@ -7296,7 +7549,7 @@ export class AnalyticsService {dateDiff('second', min(firstSeen), max(lastSeen)) AS session_durationFROM sessions FINALWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}GROUP BY psidHAVING session_duration > 0)@@ -7311,7 +7564,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`const queryEvents = `@@ -7319,7 +7572,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'custom_event'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`const queryErrors = `@@ -7327,7 +7580,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'error'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}`// Query for device/location details@@ -7344,11 +7597,11 @@ export class AnalyticsService {argMax(lc, created) AS lcFROM eventsWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND type IN ('pageview', 'custom_event', 'error')`- const params = { pid, profileId }+ const params = { pid, profileIds }const [sessionCountResult,@@ -7389,8 +7642,8 @@ export class AnalyticsService {const details = (detailsResult.data[0] || {}) as Record<string, any>return {- profileId,- isIdentified: this.isUserSuppliedProfile(profileId),+ profileId: canonicalId,+ isIdentified: this.isUserSuppliedProfile(canonicalId),sessionsCount: sessionCount.sessionsCount || 0,pageviewsCount: pageviews.pageviewsCount || 0,eventsCount: events.eventsCount || 0,@@ -7407,6 +7660,8 @@ export class AnalyticsService {profileId: string,limit = 10,): Promise<{ page: string; count: number }[]> {+ const { profileIds } = await this.resolveProfileIdentity(pid, profileId)+const query = `SELECTpg AS page,@@ -7414,7 +7669,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}GROUP BY pgORDER BY count DESCLIMIT {limit:UInt32}@@ -7423,7 +7678,7 @@ export class AnalyticsService {const { data } = await clickhouse.query({query,- query_params: { pid, profileId, limit: Number(limit) },+ query_params: { pid, profileIds, limit: Number(limit) },}).then((resultSet) => resultSet.json())@@ -7435,6 +7690,8 @@ export class AnalyticsService {profileId: string,months = 4,): Promise<{ date: string; pageviews: number; events: number }[]> {+ const { profileIds } = await this.resolveProfileIdentity(pid, profileId)+const startDate = dayjs.utc().subtract(months, 'month')@@ -7449,7 +7706,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event')- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND created >= {startDate:Date}GROUP BY dateORDER BY date ASC@@ -7458,7 +7715,7 @@ export class AnalyticsService {const { data } = await clickhouse.query({query,- query_params: { pid, profileId, startDate },+ query_params: { pid, profileIds, startDate },}).then((resultSet) => resultSet.json())@@ -7476,7 +7733,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'custom_event'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}${filtersQuery}@@ -7489,7 +7746,6 @@ export class AnalyticsService {SELECTCAST(psid, 'String') AS psidCasted,pid,- profileId,cc,os,br,@@ -7497,7 +7753,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event', 'error')- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}${scopedSessionFilter}@@ -7508,7 +7764,7 @@ export class AnalyticsService {pid: string,psids: string[],safeTimezone: string,- profileId: string,+ profileIds: string[],groupFrom: string,groupTo: string,): Promise<Map<string, any[]>> {@@ -7556,7 +7812,7 @@ export class AnalyticsService {WHEREpid = {pid:FixedString(12)}AND type IN ('pageview', 'custom_event', 'error')- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND toString(psid) IN {psids:Array(String)}AND created BETWEEN {groupFrom:String} AND {groupTo:String}@@ -7581,7 +7837,7 @@ export class AnalyticsService {pid,psids,timezone: safeTimezone,- profileId,+ profileIds,groupFrom,groupTo,},@@ -7616,6 +7872,8 @@ export class AnalyticsService {skip = 0,customEVFilterApplied = false,): Promise<object[]> {+ const { profileIds } = await this.resolveProfileIdentity(pid, profileId)+const allProfileEventsCTE = this.buildProfileSessionsEventsCTE(filtersQuery,customEVFilterApplied,@@ -7627,14 +7885,13 @@ export class AnalyticsService {SELECTpsidCasted,pid,- profileId,any(cc) AS cc_agg,any(os) AS os_agg,any(br) AS br_agg,min(created_tz) AS sessionStart,max(created_tz) AS lastActivityFROM all_profile_events- GROUP BY psidCasted, pid, profileId+ GROUP BY psidCasted, pid),pageview_counts AS (SELECT@@ -7644,7 +7901,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'pageview'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}GROUP BY psidCasted, pid@@ -7657,7 +7914,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'custom_event'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}GROUP BY psidCasted, pid@@ -7670,7 +7927,7 @@ export class AnalyticsService {FROM eventsWHERE pid = {pid:FixedString(12)}AND type = 'error'- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}AND psid IS NOT NULLAND created BETWEEN {groupFrom:String} AND {groupTo:String}GROUP BY psidCasted, pid@@ -7682,7 +7939,7 @@ export class AnalyticsService {dateDiff('second', min(firstSeen), max(lastSeen)) as avg_durationFROM sessionsWHERE pid = {pid:FixedString(12)}- AND profileId = {profileId:String}+ AND profileId IN {profileIds:Array(String)}GROUP BY psidCasted, pid)SELECT@@ -7713,7 +7970,7 @@ export class AnalyticsService {query,query_params: {pid,- profileId,+ profileIds,...paramsData.params,timezone: safeTimezone,take,@@ -7727,7 +7984,7 @@ export class AnalyticsService {pid,sessions.map((session) => String(session.psid)).filter(Boolean),safeTimezone,- profileId,+ profileIds,paramsData.params.groupFrom,paramsData.params.groupTo,)diff --git a/backend/apps/community/src/analytics/dto/identify.dto.ts b/backend/apps/community/src/analytics/dto/identify.dto.tsnew file mode 100644index 000000000..570174679--- /dev/null+++ b/backend/apps/community/src/analytics/dto/identify.dto.ts@@ -0,0 +1,25 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsString, Matches, MaxLength } from 'class-validator'+import { PID_REGEX } from '../../common/constants'++export class IdentifyDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({+ example: 'user_12345',+ required: true,+ description:+ 'A unique, stable identifier of the user (e.g. an internal user ID). It is hashed before storage; the raw value is never persisted. The current anonymous profile of the visitor gets linked to the resulting identified profile.',+ })+ @IsNotEmpty()+ @IsString()+ @MaxLength(256)+ profileId: string+}diff --git a/backend/migrations/clickhouse/2026_07_17_profile_aliases.js b/backend/migrations/clickhouse/2026_07_17_profile_aliases.jsnew file mode 100644index 000000000..22a33e171--- /dev/null+++ b/backend/migrations/clickhouse/2026_07_17_profile_aliases.js@@ -0,0 +1,18 @@+const { queriesRunner, dbName } = require('./setup')++const queries = [+ // Profile aliases table: maps anonymous (anon_) profile IDs to identified (usr_)+ // profile IDs created via the identify API. Resolved at query time with+ // argMin(userProfileId, created) so the first identification wins.+ `CREATE TABLE IF NOT EXISTS ${dbName}.profile_aliases+ (+ pid FixedString(12),+ anonProfileId String CODEC(ZSTD(3)),+ userProfileId String CODEC(ZSTD(3)),+ created DateTime('UTC') CODEC(Delta(4), LZ4)+ )+ ENGINE = ReplacingMergeTree()+ ORDER BY (pid, anonProfileId, userProfileId);`,+]++queriesRunner(queries)diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.jsindex cc079eae6..6e2e28e79 100644--- a/backend/migrations/clickhouse/initialise_database.js+++ b/backend/migrations/clickhouse/initialise_database.js@@ -83,6 +83,19 @@ const CLICKHOUSE_INIT_QUERIES = [ORDER BY (pid, psid)PARTITION BY toYYYYMM(firstSeen);`,+ // Profile aliases table: maps anonymous (anon_) profile IDs to identified (usr_)+ // profile IDs created via the identify API. Resolved at query time with+ // argMin(userProfileId, created) so the first identification wins.+ `CREATE TABLE IF NOT EXISTS ${dbName}.profile_aliases+ (+ pid FixedString(12),+ anonProfileId String CODEC(ZSTD(3)),+ userProfileId String CODEC(ZSTD(3)),+ created DateTime('UTC') CODEC(Delta(4), LZ4)+ )+ ENGINE = ReplacingMergeTree()+ ORDER BY (pid, anonProfileId, userProfileId);`,+// Feature flag evaluations table`CREATE TABLE IF NOT EXISTS ${dbName}.feature_flag_evaluations(diff --git a/docs/content/docs/analytics-dashboard/profiles-and-sessions.mdx b/docs/content/docs/analytics-dashboard/profiles-and-sessions.mdxindex f79987f8f..00e19b7d1 100644--- a/docs/content/docs/analytics-dashboard/profiles-and-sessions.mdx+++ b/docs/content/docs/analytics-dashboard/profiles-and-sessions.mdx@@ -13,7 +13,7 @@ The **Profiles** tab lists all unique visitors to your website within the selectFor each profile, you can see:-- **Profile ID**: A unique identifier for the user. If the user is identified (e.g., logged in), this might display their name or email if you have set up User Identification.+- **Profile ID**: A unique identifier for the user. Anonymous visitors get an `anon_β¦` ID derived from a monthly-rotating fingerprint; visitors identified via [`swetrix.identify()`](/swetrix-js-reference#identify) get a stable `usr_β¦` ID derived from the user ID your application supplied (hashed β the raw value is never stored).- **Status**:- **Online**: User is currently active (green indicator).- **Recently Active**: User was active in the last 30 minutes (yellow indicator).@@ -39,6 +39,16 @@ You can filter the profiles list to find specific users or segments:This is particularly useful for finding users who experienced specific bugs (e.g., filter by "Browser: Safari" if you suspect a Safari-specific issue).+### Identified users and anonymous history++When your application calls [`swetrix.identify()`](/swetrix-js-reference#identify) after a user logs in, Swetrix links the visitor's current anonymous profile to the identified one. From then on:++- The anonymous profile disappears from the list β its sessions, pageviews, events and errors are attributed to the identified profile instead.+- The session during which the user logged in is shown as a single, identified session (including the pageviews from before the login).+- The **Identified** filter includes the linked anonymous history as well.++See [visitor identification](/visitor-identification) for how the linking works and its limits.+## Profile DetailsClicking on any profile in the list opens the **Profile Details** view. This view provides a comprehensive history of that specific user's interaction with your site.diff --git a/docs/content/docs/api/events.mdx b/docs/content/docs/api/events.mdxindex 93272b79e..b736c9a8b 100644--- a/docs/content/docs/api/events.mdx+++ b/docs/content/docs/api/events.mdx@@ -104,6 +104,13 @@ All of the values are numbers in milliseconds.| ----- | -------- | -------- | ---------------------------------------------- || `pid` | `string` | `true` | A project ID to record the heartbeat event for |+### Identify event structure++| Name | Type | Required | Description |+| ----------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `pid` | `string` | `true` | A project ID to identify the visitor for |+| `profileId` | `string` | `true` | A unique, stable identifier of the user (e.g. an internal user ID), max 256 characters. It's hashed together with the project ID server-side; the raw value is never stored. |+### Revenue event structure<Callout type="info">@@ -218,6 +225,32 @@ socket.on("error", (err) => {{}```+### POST /log/identify++This endpoint identifies the visitor with your own user ID (e.g. after they log in). It links the visitor's current anonymous profile β derived from the request's IP address and User-Agent β to the identified profile derived from the supplied `profileId`, so the activity recorded before identification is attributed to the identified profile in the dashboard.++After calling it, keep sending the same `profileId` field with your pageview / custom event payloads so subsequent events are stamped with the identified profile directly. The [tracking script](/swetrix-js-reference#identify) does both automatically via `swetrix.identify()`.++Notes:++- An anonymous profile is linked to the **first** identified profile that claims it β repeated calls with the same `profileId` are idempotent, and calls with a different `profileId` won't re-link the anonymous history (but are otherwise harmless).+- Since anonymous profiles rotate monthly, the linking covers the visitor's recent anonymous activity β up to about a month back on that device and network.+- Values like `null`, `undefined`, `guest` or an empty string are rejected with a `400` error, as they would fuse unrelated visitors into a single profile.++```bash title="Request"+curl -i -X POST https://api.swetrix.com/log/identify \+ -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0" \+ -H "X-Client-IP-Address: 192.0.2.1" \+ -H "Content-Type: application/json" \+ -d '{"pid":"YOUR_PROJECT_ID","profileId":"user-12345"}'+```++```json title="Response (201 Created)"+{ "profileId": "usr_8214637194021987452" }+```++The returned `profileId` is the identified profile ID your events are stored under β the same value you'd use for [revenue attribution](/analytics-dashboard/revenue-tracking#user-attribution).+### POST /log/errorThis endpoint records error events. These error events are later aggregated in the dashboard under the Errors tab.diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdxindex 310eb6480..0805546a8 100644--- a/docs/content/docs/script-reference.mdx+++ b/docs/content/docs/script-reference.mdx@@ -29,14 +29,14 @@ swetrix.init("YOUR_PROJECT_ID", {});```-| Name | Description | Default value |-| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- |-| devMode | When set to `true`, localhost events will be sent to server. | `false` |-| disabled | When set to true, the tracking library won't send any data to server.<br />Useful for development purposes when this value is set based on '.env' var. | `false` |-| respectDNT | By setting this flag to true, we will not collect ANY kind of data about the user with the DNT setting. <br />This setting is not true by default because our service anonymises all incoming data and does not pass it on to any third parties under any circumstances. | `false` |-| apiURL | If you use Swetrix Cloud, you don't need to change this parameter. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like `[BASE_URL]/backend/v1/log`. | `'https://api.swetrix.com/log'` |-| profileId | Optional profile ID for long-term user tracking (MAU/DAU). If set, it will be used for all pageviews and events unless overridden per-call. This allows you to track users across sessions and devices. | `undefined` |-| preloadSessionReplay | Set to `true` to preload the session replay recorder after `init()`, or pass `{ rrwebUrl: "https://example.com/rrweb.min.js" }` to load it from a custom URL. Recording only starts after you call `startSessionReplay()`. | `undefined` |+| Name | Description | Default value |+| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |+| devMode | When set to `true`, localhost events will be sent to server. | `false` |+| disabled | When set to true, the tracking library won't send any data to server.<br />Useful for development purposes when this value is set based on '.env' var. | `false` |+| respectDNT | By setting this flag to true, we will not collect ANY kind of data about the user with the DNT setting. <br />This setting is not true by default because our service anonymises all incoming data and does not pass it on to any third parties under any circumstances. | `false` |+| apiURL | If you use Swetrix Cloud, you don't need to change this parameter. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like `[BASE_URL]/backend/v1/log`. | `'https://api.swetrix.com/log'` |+| profileId | Optional profile ID for long-term user tracking (MAU/DAU). If set, it will be used for all pageviews and events unless overridden per-call. This allows you to track users across sessions and devices. To also link the visitor's previous anonymous activity to this profile, use [identify()](#identify) instead. | `undefined` |+| preloadSessionReplay | Set to `true` to preload the session replay recorder after `init()`, or pass `{ rrwebUrl: "https://example.com/rrweb.min.js" }` to load it from a custom URL. Recording only starts after you call `startSessionReplay()`. | `undefined` |## track()@@ -162,6 +162,49 @@ swetrix.pageview({});```+## identify()++Identify the current visitor with your own user ID (e.g. after they log in).++Calling this function does two things:++1. **Links the anonymous history** β the visitor's current anonymous profile is linked to the identified profile server-side, so the activity they had before logging in (recent sessions, pageviews, events) is attributed to the identified profile in the dashboard.+2. **Stamps all future events** β every pageview, custom event, error, feature flag and experiment call sent after `identify()` is associated with the identified profile, exactly as if you had passed `profileId` to `init()`.++```javascript+swetrix.init("YOUR_PROJECT_ID");+swetrix.trackViews();++// After the user logs in (or on page load if they're already logged in)+swetrix.identify("user-12345");+```++Swetrix stores nothing in the browser (no cookies, no `localStorage`), so the identification only lasts for the current page life. Call `identify()` on every page load while the user is logged in β repeated calls with the same ID are deduplicated and cost you nothing extra.++<Callout type="warn">+ Use a unique, **stable** identifier β your application's internal user ID is the best choice.+ Don't use email addresses (they're personal data and can change) or values like `null`,+ `undefined` or `"guest"` (the API rejects those, as they would fuse unrelated visitors into a+ single profile). The ID you pass is hashed together with your project ID server-side and is never+ stored in its raw form.+</Callout>++A few things to know about how linking works:++- An anonymous profile is linked to the **first** identified profile that claims it. If a second person logs in with a different account on the same device and network, their identity is stamped on their own events going forward, but the shared anonymous history stays with the first account.+- Anonymous profiles rotate monthly (see [visitor identification](/visitor-identification)), so `identify()` links the visitor's recent anonymous activity β up to about a month back on that device and network.+- Identification works across devices: call `identify()` with the same ID on any device and all of that activity is unified under one profile.++## reset()++Resets the visitor's identity set via `identify()` (e.g. after they log out), so subsequent events are tracked anonymously again.++```javascript+swetrix.reset();+```++Always call this on logout if your users may share devices β otherwise the next visitor's events would be tracked under the previous user's identity.+## trackErrors()This function is used to enable automatic client-side error monitoring. It adds an `error` event listener on your site and when an error happens - send it to our APIs.@@ -449,7 +492,7 @@ swetrix.clearExperimentsCache();## getProfileId()-Gets the anonymous profile ID for the current visitor. If `profileId` was set via `init`, returns that. Otherwise, requests server to generate one from IP/UA hash.+Gets the profile ID for the current visitor. If the visitor was identified via [identify()](#identify), returns the identified (`usr_`-prefixed) profile ID events are stored under. If `profileId` was set via `init`, returns that. Otherwise, requests server to generate an anonymous one from IP/UA hash.This ID is commonly used for [revenue attribution](/analytics-dashboard/revenue-tracking#user-attribution) β pass it to your payment provider (`swetrix_profile_id` in Stripe metadata or Paddle `customData`) or include it in the request body when posting to [`/log/revenue`](/events-api#post-logrevenue) to link transactions to specific visitors.diff --git a/docs/content/docs/visitor-identification.mdx b/docs/content/docs/visitor-identification.mdxindex 43884adc3..c23c3489c 100644--- a/docs/content/docs/visitor-identification.mdx+++ b/docs/content/docs/visitor-identification.mdx@@ -130,32 +130,67 @@ have an account, or even just have a stable client-side identifier yougenerate yourself β you can tell Swetrix about it and get **perβuseraccuracy that doesn't depend on IP or UserβAgent at all.**-Pass the `profileId` to any of the tracking methods. The script-forwards it to the server, where it's salted and hashed with your-project ID before being stored β so we still never see your raw user-ID, and the ID stored in ClickHouse can't be reversed back to your-database.+The recommended way is `identify()`:```javascript-// Set it once globally on init β every pageview, custom event, error,-// feature flag, and experiment call inherits it automatically.-swetrix.init("YOUR_PROJECT_ID", {- profileId: "user-12345",-});-+swetrix.init("YOUR_PROJECT_ID");swetrix.trackViews();-// Or override per-call if you need to.-swetrix.track({- ev: "Sign up",- profileId: "user-12345",-});+// After the user logs in (or on page load if they're already logged in)+swetrix.identify("user-12345");++// On logout+swetrix.reset();```-`profileId` is supported on `init()`, `track()`, `pageview()`,+Your user ID is forwarded to the server, where it's hashed with your+project ID before being stored β so we still never see your raw user+ID, and the ID stored in ClickHouse can't be reversed back to your+database.++Alternatively, you can pass `profileId` to individual tracking methods β+it's supported on `init()`, `track()`, `pageview()`,`getFeatureFlags()` / `getFeatureFlag()`, and `getExperiments()` /`getExperiment()`. See the [script reference](/swetrix-js-reference)-for the full list.+for the full list. The difference: a plain `profileId` only stamps the+events it's passed with, while `identify()` additionally links the+visitor's anonymous history, as described below.++### How identify() links anonymous history++A visitor usually browses your site anonymously before they sign in β+so by the time you know who they are, Swetrix has already recorded+their pageviews under an anonymous `anon_β¦` fingerprint. Without extra+care, identifying them would simply start a second, separate profile+and the pre-login activity would stay orphaned.++`identify()` solves this: when called, the server links the visitor's+current anonymous profile to the identified one, and the dashboard+attributes the anonymous activity β sessions, pageviews, events,+errors β to the identified profile. Even the session during which the+user signed in stays intact: the pageviews before and after login show+up as one session under the identified profile.++The rules, in short:++- **First identification wins.** An anonymous profile can only ever be+ linked to one identified profile. If a second person logs into a+ different account on a shared device, their events are tracked under+ their own identity going forward, but the shared anonymous history+ stays with the first account. This mirrors how PostHog and other+ analytics tools guard against runaway profile merging.+- **About a month of history.** Anonymous fingerprints rotate monthly+ (see above), so the linking covers the visitor's recent anonymous+ activity on that device and network. Each month they return+ logged-in, the new anonymous fingerprint is linked too.+- **Cross-device works.** Call `identify()` with the same ID on any+ device or browser, and all of that activity is unified under one+ profile in the dashboard.+- **Nothing is stored client-side.** Swetrix remains cookieless β call+ `identify()` on every page load while the user is logged in+ (repeated calls are deduplicated), and call `reset()` on logout so+ the next person on a shared device isn't tracked under the previous+ user's identity.### What you can use as a profile ID@@ -212,8 +247,9 @@ swetrix.trackViews();// Upgrade to accurate per-user tracking once the user signs in// (or once the user grants consent in your banner, if applicable).+// This also links their pre-login anonymous activity to the profile.afterLogin((user) => {- swetrix.init("YOUR_PROJECT_ID", { profileId: user.id });+ swetrix.identify(user.id);});```@@ -236,6 +272,7 @@ chosen.| Accuracy on a typical consumer site | High β collisions are rare | Per-user accurate (for signed-in users) || Accuracy behind a school / office NAT | Lower β devices may collide | Per-user accurate || Cross-device tracking | No | Yes (same `profileId` on each) |+| Pre-login activity linked | β | Yes (via `identify()`) || Works without JavaScript | Yes (via the noscript pixel) | No (needs the JS tracker) |Pick the default for marketing sites, blogs, docs, and anywhere youdiff --git a/packages/tracker-js/README.md b/packages/tracker-js/README.mdindex e34620fa0..f89d951e2 100644--- a/packages/tracker-js/README.md+++ b/packages/tracker-js/README.md@@ -260,6 +260,20 @@ await startSessionReplay({})```+### `identify(profileId)` / `reset()`++Identify the current visitor with your own user ID (e.g. after they log in). Their current anonymous profile gets linked to the identified profile server-side, so pre-login activity is attributed to it, and all subsequent events are tracked under the identified profile.++```javascript+// After the user logs in (or on page load if they're already logged in)+identify('user-12345')++// On logout+reset()+```++Use a unique, stable identifier (e.g. an internal user ID) β not an email or other mutable / personally identifiable value. The ID is hashed server-side and never stored in raw form. Swetrix stores nothing in the browser, so call `identify()` on every page load while the user is logged in.+### Session & Profile IDs```javascriptdiff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.tsindex c06db66ac..195277bec 100644--- a/packages/tracker-js/src/Lib.ts+++ b/packages/tracker-js/src/Lib.ts@@ -356,6 +356,10 @@ export class Lib {private rrwebLoader: Promise<void> | null = nullprivate sessionReplayActions: SessionReplayActions | null = nullprivate sessionReplayInitPromise: Promise<SessionReplayActions> | null = null+ // The server-side (usr_-prefixed) profile ID returned by the identify API+ private identifiedProfileId: string | null = null+ // The last profile ID sent to the identify API (to avoid duplicate requests)+ private lastIdentifySent: string | null = nullconstructor(private projectID: string, private options?: LibOptions) {this.trackPathChange = this.trackPathChange.bind(this)@@ -646,6 +650,80 @@ export class Lib {this.cachedData = null}+ /**+ * Identify the current visitor with your own user ID (e.g. after they log in).+ *+ * The visitor's current anonymous profile gets linked to the identified+ * profile server-side, so their pre-login activity is attributed to it. All+ * events sent after this call are associated with the identified profile.+ *+ * Swetrix stores nothing in the browser, so call identify() on every page+ * load while the user is logged in. Call reset() when they log out.+ *+ * @param profileId A unique, stable identifier of the user, e.g. an internal+ * user ID. Don't use emails or other mutable / personally identifiable+ * values. The ID is hashed server-side and never stored in raw form.+ */+ async identify(profileId: string): Promise<void> {+ if (typeof profileId !== 'string' || !profileId.trim()) {+ console.error('[Swetrix] identify() expects a non-empty string profileId')+ return+ }++ const trimmed = profileId.trim()++ this.options = {+ ...this.options,+ profileId: trimmed,+ }++ if (!this.canTrack() || this.lastIdentifySent === trimmed) {+ return+ }++ this.lastIdentifySent = trimmed++ // The profile changed, so cached flags / experiments may no longer apply+ this.clearFeatureFlagsCache()++ try {+ const apiBase = this.getApiBase()+ const response = await fetch(`${apiBase}/log/identify`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ pid: this.projectID, profileId: trimmed }),+ })++ if (!response.ok) {+ return+ }++ const data = (await response.json()) as { profileId: string | null }+ this.identifiedProfileId = data.profileId || null+ } catch {+ // Keep the profileId set locally even if the identify request failed -+ // events will still be attributed to the identified profile+ }+ }++ /**+ * Resets the visitor's identity set via identify() (e.g. after they log+ * out), so subsequent events are tracked anonymously again. Important on+ * shared devices - otherwise the next visitor would be tracked under the+ * previous user's identity.+ */+ reset(): void {+ if (this.options) {+ delete this.options.profileId+ }++ this.identifiedProfileId = null+ this.lastIdentifySent = null+ this.clearFeatureFlagsCache()+ }+/*** Fetches variant assignments for running A/B test experiments returned by feature flag evaluation.* Results are cached for 5 minutes by default (shared cache with feature flags).@@ -747,6 +825,12 @@ export class Lib {* ```*/async getProfileId(): Promise<string | null> {+ // If the visitor was identified, return the server-side (usr_-prefixed)+ // profile ID, which is what events are stored under+ if (this.identifiedProfileId) {+ return this.identifiedProfileId+ }+// If profileId is already set in options, return itif (this.options?.profileId) {return this.options.profileIddiff --git a/packages/tracker-js/src/index.ts b/packages/tracker-js/src/index.tsindex 1b6ae2527..35ef87577 100644--- a/packages/tracker-js/src/index.ts+++ b/packages/tracker-js/src/index.ts@@ -278,6 +278,47 @@ export function clearExperimentsCache(): void {LIB_INSTANCE.clearExperimentsCache()}+/**+ * Identify the current visitor with your own user ID (e.g. after they log in).+ *+ * The visitor's current anonymous profile gets linked to the identified profile+ * server-side, so their pre-login activity is attributed to it. All events sent+ * after this call are associated with the identified profile.+ *+ * Swetrix stores nothing in the browser, so call identify() on every page load+ * while the user is logged in. Call reset() when they log out.+ *+ * @param profileId A unique, stable identifier of the user, e.g. an internal+ * user ID. Don't use emails or other mutable / personally identifiable values.+ * The ID is hashed server-side and never stored in raw form.+ *+ * @example+ * ```typescript+ * // After the user logs in (or on page load if they're already logged in)+ * swetrix.identify('user-12345')+ *+ * // On logout+ * swetrix.reset()+ * ```+ */+export async function identify(profileId: string): Promise<void> {+ if (!LIB_INSTANCE) return++ await LIB_INSTANCE.identify(profileId)+}++/**+ * Resets the visitor's identity set via identify() (e.g. after they log out),+ * so subsequent events are tracked anonymously again. Important on shared+ * devices - otherwise the next visitor would be tracked under the previous+ * user's identity.+ */+export function reset(): void {+ if (!LIB_INSTANCE) return++ LIB_INSTANCE.reset()+}+/*** Gets the anonymous profile ID for the current visitor.* If profileId was set via init options, returns that.diff --git a/packages/tracker-node/README.md b/packages/tracker-node/README.mdindex 85c8743fb..900907d8e 100644--- a/packages/tracker-node/README.md+++ b/packages/tracker-node/README.md@@ -433,6 +433,18 @@ const profileId = await swetrix.getProfileId('192.155.52.12', 'Mozilla/5.0...')If you set a `profileId` in the constructor options, it will be returned directly instead of generating one.+## Identifying users++Link a visitor's anonymous profile to your own user ID (e.g. after they log in), so their pre-login activity is attributed to the identified profile:++```javascript+const identifiedProfileId = await swetrix.identify('192.155.52.12', 'Mozilla/5.0...', 'user-12345')+```++Use a unique, stable identifier (e.g. an internal user ID) β not an email or other mutable / personally identifiable value. The ID is hashed server-side and never stored in raw form.++Note: unlike the browser tracker, `identify()` does not set a default `profileId` for subsequent calls β a `Swetrix` instance is shared across all visitors of your server. Keep passing `profileId` per `track()` / `trackPageView()` call.+## Session IDGet the current session ID for the visitor. Session IDs are generated server-side based on IP and user agent.diff --git a/packages/tracker-node/src/index.ts b/packages/tracker-node/src/index.tsindex 5cd73fee4..760a3092d 100644--- a/packages/tracker-node/src/index.ts+++ b/packages/tracker-node/src/index.ts@@ -557,6 +557,60 @@ export class Swetrix {}}+ /**+ * Identify a visitor with your own user ID (e.g. after they log in),+ * implements https://docs.swetrix.com/events-api#post-logidentify.+ *+ * The visitor's current anonymous profile (derived from their IP and user+ * agent) gets linked to the identified profile server-side, so their+ * pre-login activity is attributed to it.+ *+ * Note: unlike the browser tracker, this does NOT set a default profileId+ * for subsequent calls - a Swetrix instance is shared across all visitors+ * of your server. Keep passing `profileId` per track / trackPageView call.+ *+ * @param ip IP address of the visitor+ * @param userAgent User agent of the visitor+ * @param profileId A unique, stable identifier of the user, e.g. an internal+ * user ID. Don't use emails or other mutable / personally identifiable+ * values. The ID is hashed server-side and never stored in raw form.+ * @returns A promise that resolves to the identified (usr_-prefixed) profile+ * ID events are stored under, or null on error.+ */+ public async identify(ip: string, userAgent: string, profileId: string): Promise<string | null> {+ if (!this.canTrack()) {+ return null+ }++ if (typeof profileId !== 'string' || !profileId.trim()) {+ this.debug('identify() expects a non-empty string profileId', true)+ return null+ }++ try {+ const apiBase = this.getApiBase()+ const response = await fetch(`${apiBase}/log/identify`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-Client-IP-Address': ip,+ 'User-Agent': userAgent,+ },+ body: JSON.stringify({ pid: this.projectID, profileId: profileId.trim() }),+ })++ if (!response.ok) {+ return null+ }++ const data = (await response.json()) as { profileId: string | null }+ return data.profileId+ } catch (error) {+ this.debug(`Error identifying profile: ${error}`, true)+ return null+ }+ }+private async fetchFlagsAndExperiments(ip: string,userAgent: string,