π 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
Add support for profile traits
Blue Mouse40af1e5cf124
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.tsindex 2e89bd281..dd95b567e 100644--- a/backend/apps/cloud/src/analytics/analytics.controller.ts+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts@@ -3304,6 +3304,9 @@ export class AnalyticsController {* 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.+ *+ * Optional traits (email, plan, ...) are stored against the identified+ * profile and shown on its dashboard page.*/@Post('identify')@Public()@@ -3332,7 +3335,9 @@ export class AnalyticsController {return BOT_RESPONSE}- this.analyticsService.validateUserSuppliedProfileId(dto.profileId)+ const profileId = this.analyticsService.validateUserSuppliedProfileId(+ dto.profileId,+ )await this.analyticsService.validate(dto, origin, ip)@@ -3340,9 +3345,17 @@ export class AnalyticsController {dto.pid,userAgent,ip,- dto.profileId,+ profileId,)+ if (!_isEmpty(dto.traits)) {+ await this.analyticsService.saveProfileTraits(+ dto.pid,+ userProfileId,+ dto.traits,+ )+ }+const anonProfileId = await this.analyticsService.generateProfileId(dto.pid,userAgent,diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex cd2051a23..8824deb1e 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -116,6 +116,7 @@ import {import { ErrorDto } from './dto/error.dto'import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'import { DATA_DELETION_EVENT_TYPES } from './dto/data-deletion.dto'+import { MAX_USER_PROFILE_ID_LENGTH } from './dto/identify.dto'import { ProjectViewCustomEventMetaValueType } from '../project/entity/project-view-custom-event.entity'import { ProjectViewCustomEventDto } from '../project/dto/create-project-view.dto'import { UAParser } from '@ua-parser-js/pro-business'@@ -2399,11 +2400,14 @@ export class AnalyticsService {userSupplied?: string,): Promise<string> {if (userSupplied) {- const cleanId = userSupplied- .replace(AnalyticsService.PROFILE_PREFIX_ANON, '')- .replace(AnalyticsService.PROFILE_PREFIX_USER, '')- const hash = this.hashToNumericString(`${cleanId}${pid}`)- return `${AnalyticsService.PROFILE_PREFIX_USER}${hash}`+ const normalised = this.normaliseUserSuppliedProfileId(userSupplied)++ if (normalised) {+ return `${AnalyticsService.PROFILE_PREFIX_USER}${normalised}`+ }++ // Unusable identifier - fall back to the anonymous fingerprint rather+ // than fusing every visitor sending it into one profile.}const salt = await this.saltService.getSaltForProfile()@@ -2444,14 +2448,54 @@ export class AnalyticsService {'[object object]',])- validateUserSuppliedProfileId(userSupplied: string): void {- const normalised = userSupplied.trim().toLowerCase()+ // Control (\p{Cc}) and format (\p{Cf}) characters never appear in a genuine+ // identifier, but would corrupt log lines and let a profile masquerade as+ // another one in the dashboard (e.g. via a right-to-left override).+ private static readonly UNPRINTABLE_REGEX = /[\p{Cc}\p{Cf}]/u++ // Traits accumulate across identify() calls, so the number of distinct keys+ // a profile ends up with is bounded on read rather than on write.+ static readonly MAX_PROFILE_TRAITS = 100++ /**+ * Normalises a profile ID supplied by the site (via identify() or the+ * `profileId` field of an event). The value is stored as-is behind the+ * `usr_` prefix - it belongs to the site, and hashing it would only make+ * the dashboard unreadable.+ *+ * @returns the identifier to store, or null when it can't be used as one.+ */+ normaliseUserSuppliedProfileId(userSupplied: string): string | null {+ if (typeof userSupplied !== 'string') {+ return null+ }++ const trimmed = userSupplied.trim()++ if (+ !trimmed ||+ trimmed.length > MAX_USER_PROFILE_ID_LENGTH ||+ AnalyticsService.UNPRINTABLE_REGEX.test(trimmed) ||+ AnalyticsService.ILLEGAL_USER_PROFILE_IDS.has(trimmed.toLowerCase())+ ) {+ return null+ }++ return trimmed+ }++ validateUserSuppliedProfileId(userSupplied: string): string {+ const normalised = this.normaliseUserSuppliedProfileId(userSupplied)++ if (!normalised) {+ const echoed = String(userSupplied ?? '').slice(0, 64)- 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`,+ `"${echoed}" is not a valid profileId. Pass a unique, stable identifier of the user (e.g. an internal user ID) of up to ${MAX_USER_PROFILE_ID_LENGTH} characters, see https://docs.swetrix.com/visitor-identification`,)}++ return normalised}private getProfileAliasKey(pid: string, anonProfileId: string): string {@@ -2558,6 +2602,110 @@ export class AnalyticsService {return true}+ private getProfileTraitsKey(pid: string, profileId: string): string {+ return `pft:${pid}:${profileId}`+ }++ /**+ * Stores the traits (arbitrary key/value metadata a site attaches to a user -+ * email, plan, signup date, ...) of an identified profile.+ *+ * Traits are merged per key: a later call only overwrites the keys it+ * carries, and an empty value removes a trait. Storing one row per key lets+ * ClickHouse handle that without a read-modify-write cycle.+ */+ async saveProfileTraits(+ pid: string,+ profileId: string,+ traits: Record<string, string>,+ ): Promise<void> {+ const keys = _sortBy(_keys(traits))++ if (_isEmpty(keys)) {+ return+ }++ // identify() is called on every page load, so the same traits arrive over+ // and over again - skip the insert when nothing changed since the last one.+ const cacheKey = this.getProfileTraitsKey(pid, profileId)+ const fingerprint = this.hashToNumericString(+ JSON.stringify(_map(keys, (key) => [key, traits[key]])),+ )++ try {+ if ((await redis.get(cacheKey)) === fingerprint) {+ return+ }++ // Millisecond precision: `created` is the ReplacingMergeTree version, so+ // two updates of the same trait within a second must still be ordered.+ const created = dayjs.utc().format('YYYY-MM-DD HH:mm:ss.SSS')++ await clickhouse.insert({+ table: 'profile_traits',+ format: 'JSONEachRow',+ values: _map(keys, (key) => ({+ pid,+ profileId,+ key,+ value: traits[key],+ created,+ })),+ clickhouse_settings: { async_insert: 1 },+ })++ await redis.set(cacheKey, fingerprint, 'EX', 3600)+ } catch (error) {+ this.logger.error(`[saveProfileTraits] Failed to save traits: ${error}`)+ }+ }++ /**+ * Latest value of every trait set for the given profiles. Traits whose value+ * was cleared are dropped.+ */+ async getProfileTraits(+ pid: string,+ profileIds: string[],+ ): Promise<Record<string, string>> {+ if (_isEmpty(profileIds)) {+ return {}+ }++ const query = `+ SELECT key, argMax(value, created) AS value+ FROM profile_traits+ WHERE pid = {pid:FixedString(12)}+ AND profileId IN {profileIds:Array(String)}+ GROUP BY key+ HAVING value != ''+ ORDER BY key ASC+ LIMIT {limit:UInt32}+ `++ try {+ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ pid,+ profileIds,+ limit: AnalyticsService.MAX_PROFILE_TRAITS,+ },+ })+ .then((resultSet) => resultSet.json<{ key: string; value: string }>())++ return _reduce(+ data,+ (acc, { key, value }) => ({ ...acc, [key]: value }),+ {} as Record<string, string>,+ )+ } catch (error) {+ this.logger.error(`[getProfileTraits] Failed to load traits: ${error}`)+ return {}+ }+ }+/*** Resolves the full identity of a profile: the canonical profile ID to* display and every profile ID whose events belong to it.@@ -8815,6 +8963,7 @@ export class AnalyticsService {errorsResult,detailsResult,revenueResult,+ traits,] = await Promise.all([clickhouse.query({ query: querySessionCount, query_params: params })@@ -8837,6 +8986,7 @@ export class AnalyticsService {clickhouse.query({ query: queryRevenue, query_params: params }).then((resultSet) => resultSet.json()),+ this.getProfileTraits(pid, profileIds),])const sessionCount = (sessionCountResult.data[0] || {}) as Record<@@ -8853,6 +9003,7 @@ export class AnalyticsService {return {profileId: canonicalId,isIdentified: this.isUserSuppliedProfile(canonicalId),+ traits,sessionsCount: sessionCount.sessionsCount || 0,pageviewsCount: pageviews.pageviewsCount || 0,eventsCount: events.eventsCount || 0,diff --git a/backend/apps/cloud/src/analytics/dto/get-profile.dto.ts b/backend/apps/cloud/src/analytics/dto/get-profile.dto.tsindex 6962d2bac..52d1d6d88 100644--- a/backend/apps/cloud/src/analytics/dto/get-profile.dto.ts+++ b/backend/apps/cloud/src/analytics/dto/get-profile.dto.ts@@ -13,6 +13,7 @@ import {import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'import { PID_REGEX } from '../../common/constants'import { GetDataDto } from './getData.dto'+import { MAX_STORED_PROFILE_ID_LENGTH } from './identify.dto'export class GetProfileDto {@ApiProperty({@@ -27,11 +28,11 @@ export class GetProfileDto {@ApiProperty({required: true,description: 'The profile ID',- maxLength: 256,+ maxLength: MAX_STORED_PROFILE_ID_LENGTH,})@IsNotEmpty()@IsString()- @MaxLength(256)+ @MaxLength(MAX_STORED_PROFILE_ID_LENGTH)profileId: string@ApiProperty({@@ -53,11 +54,11 @@ export class GetProfileSessionsDto extends PickType(GetDataDto, [@ApiProperty({required: true,description: 'The profile ID',- maxLength: 256,+ maxLength: MAX_STORED_PROFILE_ID_LENGTH,})@IsNotEmpty()@IsString()- @MaxLength(256)+ @MaxLength(MAX_STORED_PROFILE_ID_LENGTH)profileId: string@ApiProperty({ required: false, default: 30 })diff --git a/backend/apps/cloud/src/analytics/dto/identify.dto.ts b/backend/apps/cloud/src/analytics/dto/identify.dto.tsindex 570174679..b37614069 100644--- a/backend/apps/cloud/src/analytics/dto/identify.dto.ts+++ b/backend/apps/cloud/src/analytics/dto/identify.dto.ts@@ -1,7 +1,110 @@+import _keys from 'lodash/keys'+import _some from 'lodash/some'+import _values from 'lodash/values'import { ApiProperty } from '@nestjs/swagger'-import { IsNotEmpty, IsString, Matches, MaxLength } from 'class-validator'+import { Transform } from 'class-transformer'+import {+ IsNotEmpty,+ IsObject,+ IsOptional,+ IsString,+ Matches,+ MaxLength,+ Validate,+ ValidatorConstraint,+ ValidatorConstraintInterface,+} from 'class-validator'import { PID_REGEX } from '../../common/constants'+// The raw identifier a site passes to identify() (or as `profileId` on an+// event). It is stored as provided, behind the `usr_` prefix.+export const MAX_USER_PROFILE_ID_LENGTH = 256+export const MAX_STORED_PROFILE_ID_LENGTH =+ MAX_USER_PROFILE_ID_LENGTH + 'usr_'.length++const MAX_TRAITS_KEYS = 50+const MAX_TRAIT_KEY_LENGTH = 128+const MAX_TRAITS_TOTAL_LENGTH = 2000++@ValidatorConstraint()+class TraitsKeysQuantity implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ return _keys(traits).length <= MAX_TRAITS_KEYS+ }+}++// Control / format characters never appear in a genuine trait name, but would+// corrupt the dashboard rendering them.+const UNPRINTABLE_REGEX = /[\p{Cc}\p{Cf}]/u++@ValidatorConstraint()+class TraitsKeyFormat implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ return !_some(+ _keys(traits),+ (key) =>+ !key.trim() ||+ key.length > MAX_TRAIT_KEY_LENGTH ||+ UNPRINTABLE_REGEX.test(key),+ )+ }+}++@ValidatorConstraint()+class TraitsValueType implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ return !_some(_values(traits), (value) => typeof value !== 'string')+ }+}++@ValidatorConstraint()+class TraitsSizeLimit implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ let totalSize = 0++ for (const key of _keys(traits)) {+ const value = traits[key]+ totalSize += key.length + (typeof value === 'string' ? value.length : 0)++ if (totalSize > MAX_TRAITS_TOTAL_LENGTH) {+ return false+ }+ }++ return true+ }+}++/**+ * Traits are free-form, so accept the primitives a JSON payload naturally+ * carries and store them as strings. `null` / `undefined` mean "remove this+ * trait" and are normalised to an empty value.+ */+function transformTraits(value: any): any {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ return value+ }++ const transformed: Record<string, any> = {}++ for (const key of _keys(value)) {+ const trait = value[key]++ if (trait === null || trait === undefined) {+ transformed[key.trim()] = ''+ } else if (typeof trait === 'number' || typeof trait === 'boolean') {+ transformed[key.trim()] = String(trait)+ } else if (typeof trait === 'string') {+ transformed[key.trim()] = trait.trim()+ } else {+ // Objects and arrays are left as-is for the validation below to reject+ transformed[key.trim()] = trait+ }+ }++ return transformed+}+export class IdentifyDto {@ApiProperty({example: 'aUn1quEid-3',@@ -16,10 +119,36 @@ export class IdentifyDto {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.',+ 'A unique, stable identifier of the user (e.g. an internal user ID), stored as provided. The current anonymous profile of the visitor gets linked to the resulting identified profile.',})@IsNotEmpty()@IsString()- @MaxLength(256)+ @MaxLength(MAX_USER_PROFILE_ID_LENGTH)profileId: string++ @ApiProperty({+ example: {+ email: '[email protected]',+ plan: 'premium',+ },+ required: false,+ description:+ 'Traits of the identified user, displayed on their profile. Values must be primitive JSON types and are stored as strings; a null value removes the trait.',+ })+ @IsOptional()+ @IsObject()+ @Transform(({ value }) => transformTraits(value))+ @Validate(TraitsKeysQuantity, {+ message: `Traits object can't have more than ${MAX_TRAITS_KEYS} keys`,+ })+ @Validate(TraitsKeyFormat, {+ message: `Traits keys must be non-empty and no longer than ${MAX_TRAIT_KEY_LENGTH} characters`,+ })+ @Validate(TraitsValueType, {+ message: 'All of traits object values must be primitive JSON values',+ })+ @Validate(TraitsSizeLimit, {+ message: `Traits object can't have keys and values with total length more than ${MAX_TRAITS_TOTAL_LENGTH} characters`,+ })+ traits?: Record<string, string>}diff --git a/backend/apps/cloud/src/analytics/v2/dto/entities.dto.ts b/backend/apps/cloud/src/analytics/v2/dto/entities.dto.tsindex b8579e767..1f1534853 100644--- a/backend/apps/cloud/src/analytics/v2/dto/entities.dto.ts+++ b/backend/apps/cloud/src/analytics/v2/dto/entities.dto.ts@@ -9,10 +9,12 @@ import {IsOptional,IsString,Max,+ MaxLength,Min,} from 'class-validator'import { TimeBucketType } from '../../dto/getData.dto'+import { MAX_STORED_PROFILE_ID_LENGTH } from '../../dto/identify.dto'import { V2BaseQueryDto, V2ProjectParamsDto } from './v2-base.dto'export const V2_MAX_ENTITY_LIMIT = 150@@ -138,6 +140,7 @@ export class V2ProfileParamsDto extends V2ProjectParamsDto {@ApiProperty({ description: 'The profile identifier' })@IsNotEmpty()@IsString()+ @MaxLength(MAX_STORED_PROFILE_ID_LENGTH)profileId: string}diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.tsindex 2c18e3130..b2273605b 100644--- a/backend/apps/cloud/src/project/project.controller.ts+++ b/backend/apps/cloud/src/project/project.controller.ts@@ -753,6 +753,8 @@ export class ProjectController {const queries = ['ALTER TABLE events DELETE WHERE pid={pid:FixedString(12)}','ALTER TABLE error_statuses DELETE WHERE pid={pid:FixedString(12)}',+ 'ALTER TABLE profile_aliases DELETE WHERE pid={pid:FixedString(12)}',+ 'ALTER TABLE profile_traits DELETE WHERE pid={pid:FixedString(12)}',]try {@@ -1641,6 +1643,8 @@ export class ProjectController {const queries = ['ALTER TABLE events DELETE WHERE pid={pid:FixedString(12)}','ALTER TABLE error_statuses DELETE WHERE pid={pid:FixedString(12)}',+ 'ALTER TABLE profile_aliases DELETE WHERE pid={pid:FixedString(12)}',+ 'ALTER TABLE profile_traits DELETE WHERE pid={pid:FixedString(12)}',]try {diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.tsindex 071ff3a8c..dac927f35 100644--- a/backend/apps/cloud/src/project/project.service.ts+++ b/backend/apps/cloud/src/project/project.service.ts@@ -514,6 +514,8 @@ export class ProjectService {const queries = ['ALTER TABLE events DELETE WHERE pid IN ({pids:Array(FixedString(12))})','ALTER TABLE error_statuses DELETE WHERE pid IN ({pids:Array(FixedString(12))})',+ 'ALTER TABLE profile_aliases DELETE WHERE pid IN ({pids:Array(FixedString(12))})',+ 'ALTER TABLE profile_traits DELETE WHERE pid IN ({pids:Array(FixedString(12))})',]await Promise.all(diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.tsindex e1f18c5b6..60cb697bd 100644--- a/backend/apps/community/src/analytics/analytics.controller.ts+++ b/backend/apps/community/src/analytics/analytics.controller.ts@@ -2795,6 +2795,9 @@ export class AnalyticsController {* 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.+ *+ * Optional traits (email, plan, ...) are stored against the identified+ * profile and shown on its dashboard page.*/@Post('identify')@Public()@@ -2823,7 +2826,9 @@ export class AnalyticsController {return BOT_RESPONSE}- this.analyticsService.validateUserSuppliedProfileId(dto.profileId)+ const profileId = this.analyticsService.validateUserSuppliedProfileId(+ dto.profileId,+ )await this.analyticsService.validate(dto, origin, ip)@@ -2831,9 +2836,17 @@ export class AnalyticsController {dto.pid,userAgent,ip,- dto.profileId,+ profileId,)+ if (!_isEmpty(dto.traits)) {+ await this.analyticsService.saveProfileTraits(+ dto.pid,+ userProfileId,+ dto.traits,+ )+ }+const anonProfileId = await this.analyticsService.generateProfileId(dto.pid,userAgent,diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex 9321b44b4..cf1250ddb 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -102,6 +102,7 @@ import {import { ErrorDto } from './dto/error.dto'import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'import { DATA_DELETION_EVENT_TYPES } from './dto/data-deletion.dto'+import { MAX_USER_PROFILE_ID_LENGTH } from './dto/identify.dto'import { ProjectViewCustomEventMetaValueType } from '../project/entity/project-view-custom-event.entity'import { ProjectViewCustomEventDto } from '../project/dto/create-project-view.dto'import { UAParser } from '@ua-parser-js/pro-business'@@ -2040,11 +2041,14 @@ export class AnalyticsService {userSupplied?: string,): Promise<string> {if (userSupplied) {- const cleanId = userSupplied- .replace(AnalyticsService.PROFILE_PREFIX_ANON, '')- .replace(AnalyticsService.PROFILE_PREFIX_USER, '')- const hash = this.hashToNumericString(`${cleanId}${pid}`)- return `${AnalyticsService.PROFILE_PREFIX_USER}${hash}`+ const normalised = this.normaliseUserSuppliedProfileId(userSupplied)++ if (normalised) {+ return `${AnalyticsService.PROFILE_PREFIX_USER}${normalised}`+ }++ // Unusable identifier - fall back to the anonymous fingerprint rather+ // than fusing every visitor sending it into one profile.}const salt = await this.saltService.getSaltForProfile()@@ -2085,14 +2089,54 @@ export class AnalyticsService {'[object object]',])- validateUserSuppliedProfileId(userSupplied: string): void {- const normalised = userSupplied.trim().toLowerCase()+ // Control (\p{Cc}) and format (\p{Cf}) characters never appear in a genuine+ // identifier, but would corrupt log lines and let a profile masquerade as+ // another one in the dashboard (e.g. via a right-to-left override).+ private static readonly UNPRINTABLE_REGEX = /[\p{Cc}\p{Cf}]/u++ // Traits accumulate across identify() calls, so the number of distinct keys+ // a profile ends up with is bounded on read rather than on write.+ static readonly MAX_PROFILE_TRAITS = 100++ /**+ * Normalises a profile ID supplied by the site (via identify() or the+ * `profileId` field of an event). The value is stored as-is behind the+ * `usr_` prefix - it belongs to the site, and hashing it would only make+ * the dashboard unreadable.+ *+ * @returns the identifier to store, or null when it can't be used as one.+ */+ normaliseUserSuppliedProfileId(userSupplied: string): string | null {+ if (typeof userSupplied !== 'string') {+ return null+ }++ const trimmed = userSupplied.trim()++ if (+ !trimmed ||+ trimmed.length > MAX_USER_PROFILE_ID_LENGTH ||+ AnalyticsService.UNPRINTABLE_REGEX.test(trimmed) ||+ AnalyticsService.ILLEGAL_USER_PROFILE_IDS.has(trimmed.toLowerCase())+ ) {+ return null+ }++ return trimmed+ }++ validateUserSuppliedProfileId(userSupplied: string): string {+ const normalised = this.normaliseUserSuppliedProfileId(userSupplied)++ if (!normalised) {+ const echoed = String(userSupplied ?? '').slice(0, 64)- 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`,+ `"${echoed}" is not a valid profileId. Pass a unique, stable identifier of the user (e.g. an internal user ID) of up to ${MAX_USER_PROFILE_ID_LENGTH} characters, see https://docs.swetrix.com/visitor-identification`,)}++ return normalised}private getProfileAliasKey(pid: string, anonProfileId: string): string {@@ -2199,6 +2243,110 @@ export class AnalyticsService {return true}+ private getProfileTraitsKey(pid: string, profileId: string): string {+ return `pft:${pid}:${profileId}`+ }++ /**+ * Stores the traits (arbitrary key/value metadata a site attaches to a user -+ * email, plan, signup date, ...) of an identified profile.+ *+ * Traits are merged per key: a later call only overwrites the keys it+ * carries, and an empty value removes a trait. Storing one row per key lets+ * ClickHouse handle that without a read-modify-write cycle.+ */+ async saveProfileTraits(+ pid: string,+ profileId: string,+ traits: Record<string, string>,+ ): Promise<void> {+ const keys = _sortBy(_keys(traits))++ if (_isEmpty(keys)) {+ return+ }++ // identify() is called on every page load, so the same traits arrive over+ // and over again - skip the insert when nothing changed since the last one.+ const cacheKey = this.getProfileTraitsKey(pid, profileId)+ const fingerprint = this.hashToNumericString(+ JSON.stringify(_map(keys, (key) => [key, traits[key]])),+ )++ try {+ if ((await redis.get(cacheKey)) === fingerprint) {+ return+ }++ // Millisecond precision: `created` is the ReplacingMergeTree version, so+ // two updates of the same trait within a second must still be ordered.+ const created = dayjs.utc().format('YYYY-MM-DD HH:mm:ss.SSS')++ await clickhouse.insert({+ table: 'profile_traits',+ format: 'JSONEachRow',+ values: _map(keys, (key) => ({+ pid,+ profileId,+ key,+ value: traits[key],+ created,+ })),+ clickhouse_settings: { async_insert: 1 },+ })++ await redis.set(cacheKey, fingerprint, 'EX', 3600)+ } catch (error) {+ this.logger.error(`[saveProfileTraits] Failed to save traits: ${error}`)+ }+ }++ /**+ * Latest value of every trait set for the given profiles. Traits whose value+ * was cleared are dropped.+ */+ async getProfileTraits(+ pid: string,+ profileIds: string[],+ ): Promise<Record<string, string>> {+ if (_isEmpty(profileIds)) {+ return {}+ }++ const query = `+ SELECT key, argMax(value, created) AS value+ FROM profile_traits+ WHERE pid = {pid:FixedString(12)}+ AND profileId IN {profileIds:Array(String)}+ GROUP BY key+ HAVING value != ''+ ORDER BY key ASC+ LIMIT {limit:UInt32}+ `++ try {+ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ pid,+ profileIds,+ limit: AnalyticsService.MAX_PROFILE_TRAITS,+ },+ })+ .then((resultSet) => resultSet.json<{ key: string; value: string }>())++ return _reduce(+ data,+ (acc, { key, value }) => ({ ...acc, [key]: value }),+ {} as Record<string, string>,+ )+ } catch (error) {+ this.logger.error(`[getProfileTraits] Failed to load traits: ${error}`)+ return {}+ }+ }+/*** Resolves the full identity of a profile: the canonical profile ID to* display and every profile ID whose events belong to it.@@ -7620,6 +7768,7 @@ export class AnalyticsService {eventsResult,errorsResult,detailsResult,+ traits,] = await Promise.all([clickhouse.query({ query: querySessionCount, query_params: params })@@ -7639,6 +7788,7 @@ export class AnalyticsService {clickhouse.query({ query: queryDetails, query_params: params }).then((resultSet) => resultSet.json()),+ this.getProfileTraits(pid, profileIds),])const sessionCount = (sessionCountResult.data[0] || {}) as Record<@@ -7654,6 +7804,7 @@ export class AnalyticsService {return {profileId: canonicalId,isIdentified: this.isUserSuppliedProfile(canonicalId),+ traits,sessionsCount: sessionCount.sessionsCount || 0,pageviewsCount: pageviews.pageviewsCount || 0,eventsCount: events.eventsCount || 0,diff --git a/backend/apps/community/src/analytics/dto/get-profile.dto.ts b/backend/apps/community/src/analytics/dto/get-profile.dto.tsindex 6962d2bac..52d1d6d88 100644--- a/backend/apps/community/src/analytics/dto/get-profile.dto.ts+++ b/backend/apps/community/src/analytics/dto/get-profile.dto.ts@@ -13,6 +13,7 @@ import {import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'import { PID_REGEX } from '../../common/constants'import { GetDataDto } from './getData.dto'+import { MAX_STORED_PROFILE_ID_LENGTH } from './identify.dto'export class GetProfileDto {@ApiProperty({@@ -27,11 +28,11 @@ export class GetProfileDto {@ApiProperty({required: true,description: 'The profile ID',- maxLength: 256,+ maxLength: MAX_STORED_PROFILE_ID_LENGTH,})@IsNotEmpty()@IsString()- @MaxLength(256)+ @MaxLength(MAX_STORED_PROFILE_ID_LENGTH)profileId: string@ApiProperty({@@ -53,11 +54,11 @@ export class GetProfileSessionsDto extends PickType(GetDataDto, [@ApiProperty({required: true,description: 'The profile ID',- maxLength: 256,+ maxLength: MAX_STORED_PROFILE_ID_LENGTH,})@IsNotEmpty()@IsString()- @MaxLength(256)+ @MaxLength(MAX_STORED_PROFILE_ID_LENGTH)profileId: string@ApiProperty({ required: false, default: 30 })diff --git a/backend/apps/community/src/analytics/dto/identify.dto.ts b/backend/apps/community/src/analytics/dto/identify.dto.tsindex 570174679..b37614069 100644--- a/backend/apps/community/src/analytics/dto/identify.dto.ts+++ b/backend/apps/community/src/analytics/dto/identify.dto.ts@@ -1,7 +1,110 @@+import _keys from 'lodash/keys'+import _some from 'lodash/some'+import _values from 'lodash/values'import { ApiProperty } from '@nestjs/swagger'-import { IsNotEmpty, IsString, Matches, MaxLength } from 'class-validator'+import { Transform } from 'class-transformer'+import {+ IsNotEmpty,+ IsObject,+ IsOptional,+ IsString,+ Matches,+ MaxLength,+ Validate,+ ValidatorConstraint,+ ValidatorConstraintInterface,+} from 'class-validator'import { PID_REGEX } from '../../common/constants'+// The raw identifier a site passes to identify() (or as `profileId` on an+// event). It is stored as provided, behind the `usr_` prefix.+export const MAX_USER_PROFILE_ID_LENGTH = 256+export const MAX_STORED_PROFILE_ID_LENGTH =+ MAX_USER_PROFILE_ID_LENGTH + 'usr_'.length++const MAX_TRAITS_KEYS = 50+const MAX_TRAIT_KEY_LENGTH = 128+const MAX_TRAITS_TOTAL_LENGTH = 2000++@ValidatorConstraint()+class TraitsKeysQuantity implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ return _keys(traits).length <= MAX_TRAITS_KEYS+ }+}++// Control / format characters never appear in a genuine trait name, but would+// corrupt the dashboard rendering them.+const UNPRINTABLE_REGEX = /[\p{Cc}\p{Cf}]/u++@ValidatorConstraint()+class TraitsKeyFormat implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ return !_some(+ _keys(traits),+ (key) =>+ !key.trim() ||+ key.length > MAX_TRAIT_KEY_LENGTH ||+ UNPRINTABLE_REGEX.test(key),+ )+ }+}++@ValidatorConstraint()+class TraitsValueType implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ return !_some(_values(traits), (value) => typeof value !== 'string')+ }+}++@ValidatorConstraint()+class TraitsSizeLimit implements ValidatorConstraintInterface {+ validate(traits: Record<string, string>) {+ let totalSize = 0++ for (const key of _keys(traits)) {+ const value = traits[key]+ totalSize += key.length + (typeof value === 'string' ? value.length : 0)++ if (totalSize > MAX_TRAITS_TOTAL_LENGTH) {+ return false+ }+ }++ return true+ }+}++/**+ * Traits are free-form, so accept the primitives a JSON payload naturally+ * carries and store them as strings. `null` / `undefined` mean "remove this+ * trait" and are normalised to an empty value.+ */+function transformTraits(value: any): any {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ return value+ }++ const transformed: Record<string, any> = {}++ for (const key of _keys(value)) {+ const trait = value[key]++ if (trait === null || trait === undefined) {+ transformed[key.trim()] = ''+ } else if (typeof trait === 'number' || typeof trait === 'boolean') {+ transformed[key.trim()] = String(trait)+ } else if (typeof trait === 'string') {+ transformed[key.trim()] = trait.trim()+ } else {+ // Objects and arrays are left as-is for the validation below to reject+ transformed[key.trim()] = trait+ }+ }++ return transformed+}+export class IdentifyDto {@ApiProperty({example: 'aUn1quEid-3',@@ -16,10 +119,36 @@ export class IdentifyDto {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.',+ 'A unique, stable identifier of the user (e.g. an internal user ID), stored as provided. The current anonymous profile of the visitor gets linked to the resulting identified profile.',})@IsNotEmpty()@IsString()- @MaxLength(256)+ @MaxLength(MAX_USER_PROFILE_ID_LENGTH)profileId: string++ @ApiProperty({+ example: {+ email: '[email protected]',+ plan: 'premium',+ },+ required: false,+ description:+ 'Traits of the identified user, displayed on their profile. Values must be primitive JSON types and are stored as strings; a null value removes the trait.',+ })+ @IsOptional()+ @IsObject()+ @Transform(({ value }) => transformTraits(value))+ @Validate(TraitsKeysQuantity, {+ message: `Traits object can't have more than ${MAX_TRAITS_KEYS} keys`,+ })+ @Validate(TraitsKeyFormat, {+ message: `Traits keys must be non-empty and no longer than ${MAX_TRAIT_KEY_LENGTH} characters`,+ })+ @Validate(TraitsValueType, {+ message: 'All of traits object values must be primitive JSON values',+ })+ @Validate(TraitsSizeLimit, {+ message: `Traits object can't have keys and values with total length more than ${MAX_TRAITS_TOTAL_LENGTH} characters`,+ })+ traits?: Record<string, string>}diff --git a/backend/apps/community/src/analytics/v2/dto/entities.dto.ts b/backend/apps/community/src/analytics/v2/dto/entities.dto.tsindex b8579e767..1f1534853 100644--- a/backend/apps/community/src/analytics/v2/dto/entities.dto.ts+++ b/backend/apps/community/src/analytics/v2/dto/entities.dto.ts@@ -9,10 +9,12 @@ import {IsOptional,IsString,Max,+ MaxLength,Min,} from 'class-validator'import { TimeBucketType } from '../../dto/getData.dto'+import { MAX_STORED_PROFILE_ID_LENGTH } from '../../dto/identify.dto'import { V2BaseQueryDto, V2ProjectParamsDto } from './v2-base.dto'export const V2_MAX_ENTITY_LIMIT = 150@@ -138,6 +140,7 @@ export class V2ProfileParamsDto extends V2ProjectParamsDto {@ApiProperty({ description: 'The profile identifier' })@IsNotEmpty()@IsString()+ @MaxLength(MAX_STORED_PROFILE_ID_LENGTH)profileId: string}diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.tsindex 1930a37df..74bcb7a40 100644--- a/backend/apps/community/src/project/project.controller.ts+++ b/backend/apps/community/src/project/project.controller.ts@@ -1027,6 +1027,14 @@ export class ProjectController {query: `ALTER TABLE error_statuses DELETE WHERE pid={pid:FixedString(12)}`,query_params: { pid: id },})+ await clickhouse.command({+ query: `ALTER TABLE profile_aliases DELETE WHERE pid={pid:FixedString(12)}`,+ query_params: { pid: id },+ })+ await clickhouse.command({+ query: `ALTER TABLE profile_traits DELETE WHERE pid={pid:FixedString(12)}`,+ query_params: { pid: id },+ })await deleteProjectRedis(id)return 'Project deleted successfully'} catch (e) {diff --git a/backend/apps/community/src/user/user.controller.ts b/backend/apps/community/src/user/user.controller.tsindex c984d862d..21223829f 100644--- a/backend/apps/community/src/user/user.controller.ts+++ b/backend/apps/community/src/user/user.controller.ts@@ -184,6 +184,8 @@ export class UserController {const queries = ['ALTER TABLE events DELETE WHERE pid IN ({pids:Array(FixedString(12))})','ALTER TABLE error_statuses DELETE WHERE pid IN ({pids:Array(FixedString(12))})',+ 'ALTER TABLE profile_aliases DELETE WHERE pid IN ({pids:Array(FixedString(12))})',+ 'ALTER TABLE profile_traits DELETE WHERE pid IN ({pids:Array(FixedString(12))})',]await deleteProjectsByUserIdClickhouse(id)const promises = _map(queries, async (query) =>diff --git a/backend/migrations/clickhouse/2026_07_28_profile_traits.js b/backend/migrations/clickhouse/2026_07_28_profile_traits.jsnew file mode 100644index 000000000..ecfa761a5--- /dev/null+++ b/backend/migrations/clickhouse/2026_07_28_profile_traits.js@@ -0,0 +1,20 @@+const { queriesRunner, dbName } = require('./setup')++const queries = [+ // Traits (arbitrary key/value metadata - email, plan, ...) attached to+ // identified profiles via the identify API. One row per key so traits merge+ // across calls without a read-modify-write cycle; the latest value of each+ // key wins and an empty value means the trait was removed.+ `CREATE TABLE IF NOT EXISTS ${dbName}.profile_traits+ (+ pid FixedString(12),+ profileId String CODEC(ZSTD(3)),+ key String CODEC(ZSTD(3)),+ value String CODEC(ZSTD(3)),+ created DateTime64(3, 'UTC') CODEC(Delta(4), LZ4)+ )+ ENGINE = ReplacingMergeTree(created)+ ORDER BY (pid, profileId, key);`,+]++queriesRunner(queries)diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.jsindex 6e2e28e79..d60828387 100644--- a/backend/migrations/clickhouse/initialise_database.js+++ b/backend/migrations/clickhouse/initialise_database.js@@ -96,6 +96,21 @@ const CLICKHOUSE_INIT_QUERIES = [ENGINE = ReplacingMergeTree()ORDER BY (pid, anonProfileId, userProfileId);`,+ // Profile traits table: arbitrary key/value metadata (email, plan, ...) set+ // for identified profiles via the identify API. One row per key so traits+ // merge across calls; the latest value of each key wins and an empty value+ // means the trait was removed.+ `CREATE TABLE IF NOT EXISTS ${dbName}.profile_traits+ (+ pid FixedString(12),+ profileId String CODEC(ZSTD(3)),+ key String CODEC(ZSTD(3)),+ value String CODEC(ZSTD(3)),+ created DateTime64(3, 'UTC') CODEC(Delta(4), LZ4)+ )+ ENGINE = ReplacingMergeTree(created)+ ORDER BY (pid, profileId, key);`,+// Feature flag evaluations table`CREATE TABLE IF NOT EXISTS ${dbName}.feature_flag_evaluations(diff --git a/docs/.gitignore b/docs/.gitignoreindex ca8600674..52dc280d6 100644--- a/docs/.gitignore+++ b/docs/.gitignore@@ -2,3 +2,4 @@ node_modules/.next/.source/out/+.static-archive/diff --git a/docs/content/docs/analytics-dashboard/profiles-and-sessions.mdx b/docs/content/docs/analytics-dashboard/profiles-and-sessions.mdxindex 00e19b7d1..8d26a2ad0 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. 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).+- **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 β the user ID your application supplied, stored as provided.- **Status**:- **Online**: User is currently active (green indicator).- **Recently Active**: User was active in the last 30 minutes (yellow indicator).@@ -62,6 +62,12 @@ The top section shows a summary of the user:- **Total Revenue**: If you are tracking revenue, the total amount generated by this user.- **Activity Calendar**: A heat map visualization (similar to GitHub contributions) showing the user's activity intensity over the last few months. This helps you quickly identify when the user is most active.+### User Traits++If your application passes traits when calling [`swetrix.identify()`](/swetrix-js-reference#identify) β an email address, a name, a plan, or anything else you find useful β they're listed in a **User traits** section on the profile. The section is hidden for profiles that have none.++Traits are merged per key across calls, so the profile always shows the latest value your application sent for each one. See [visitor identification](/visitor-identification#user-traits) for the limits and how to remove a trait.+### Session HistoryBelow the overview, you will see a list of all **Sessions** for this user. A session represents a continuous period of activity.diff --git a/docs/content/docs/api/events.mdx b/docs/content/docs/api/events.mdxindex b736c9a8b..8bc3d07ff 100644--- a/docs/content/docs/api/events.mdx+++ b/docs/content/docs/api/events.mdx@@ -106,10 +106,11 @@ All of the values are numbers in milliseconds.### 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. |+| 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 stored as provided, behind a `usr_` prefix. |+| `traits` | `object` | `false` | A `key` / `value` pair of metadata describing the user, for example `{ email: '[email protected]', plan: 'premium' }`. Values must be a primitive type (string, number, boolean, null) which will be converted to a string; `null` removes a trait. Max 50 keys, 128 characters per key, and 2000 characters for all keys and values combined. |### Revenue event structure@@ -236,17 +237,18 @@ 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.+- The optional `traits` object is stored against the identified profile and displayed on its dashboard page. Traits are merged per key, so a later call only overwrites the keys it carries and an empty / `null` value removes one.```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"}'+ -d '{"pid":"YOUR_PROJECT_ID","profileId":"user-12345","traits":{"email":"[email protected]","plan":"premium"}}'``````json title="Response (201 Created)"-{ "profileId": "usr_8214637194021987452" }+{ "profileId": "usr_user-12345" }```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).diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdxindex 0805546a8..5d09bd03d 100644--- a/docs/content/docs/script-reference.mdx+++ b/docs/content/docs/script-reference.mdx@@ -181,12 +181,24 @@ 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.+You can also pass **traits** β arbitrary key / value metadata shown in the "User traits" section of the user's profile:++```javascript+swetrix.identify("user-12345", {+ email: "[email protected]",+ name: "John Doe",+ plan: "premium",+});+```++Traits are merged per key, so a later call only overwrites the keys it carries and `null` removes a trait. Per call you can send up to 50 keys, keys of up to 128 characters, and 2000 characters for all keys and values combined; values must be strings, numbers, booleans or `null` and are stored as strings.+<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.+ Don't use 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 stored as provided (behind a `usr_`+ prefix) and shown in your dashboard, so if you want a user's email on their profile, send it as a+ trait rather than using it as the ID.</Callout>A few things to know about how linking works:@@ -195,6 +207,16 @@ A few things to know about how linking works:- 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.+## setTraits()++Updates the traits of an already identified visitor without repeating their user ID. Only the keys you pass are touched; pass `null` to remove a trait.++```javascript+swetrix.setTraits({ plan: "enterprise", trialEndsAt: null });+```++Requires [`identify()`](#identify) (or a `profileId` on `init()`) to have been called first β otherwise there's no profile to attach the traits to and the call is a no-op. The same per-call limits as `identify()` apply.+## reset()Resets the visitor's identity set via `identify()` (e.g. after they log out), so subsequent events are tracked anonymously again.diff --git a/docs/content/docs/visitor-identification.mdx b/docs/content/docs/visitor-identification.mdxindex c23c3489c..0d20eaaae 100644--- a/docs/content/docs/visitor-identification.mdx+++ b/docs/content/docs/visitor-identification.mdx@@ -143,10 +143,10 @@ swetrix.identify("user-12345");swetrix.reset();```-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.+Your user ID is stored exactly as you send it, behind a `usr_` prefix β+so the profile that shows up in your dashboard is `usr_user-12345`, and+you can look a user up by the same ID you use in your own database.+Only send identifiers you're comfortable seeing in the dashboard.Alternatively, you can pass `profileId` to individual tracking methods βit's supported on `init()`, `track()`, `pageview()`,@@ -204,15 +204,51 @@ choices:works for anonymous users too, but because _you_ (not Swetrix) arenow setting a persistent identifier on the device, you should reviewwhether your local privacy regulations require user consent for it.-- **A hashed email or account identifier** if you already use one for- other systems. Just make sure the hash is stable for the same user.+- **A pseudonymous account identifier** if you already use one for other+ systems. Just make sure it's stable for the same user.- **A device or installation ID** in mobile or desktop apps embeddinga webview.<Callout type="warn">- Don't pass raw email addresses, full names, phone numbers, or any other personal data as- `profileId`. Hash or pseudonymise it on your side first. Swetrix anonymises whatever it receives,- but the cleanest approach is to never send PII in the first place.+ The `profileId` is stored as provided β Swetrix doesn't hash or otherwise transform it. Prefer an+ opaque internal ID over email addresses, full names or phone numbers, and pseudonymise on your+ side if your privacy policy requires it. If you do want a user's email on their profile, attach it+ as a [trait](#user-traits) instead of using it as the ID.+</Callout>++### User traits++An ID on its own tells you _that_ two sessions belong to the same+person, not _who_ they are. Pass **traits** alongside it and Swetrix+shows them in a "User traits" section on the profile page:++```javascript+swetrix.identify("user-12345", {+ email: "[email protected]",+ name: "John Doe",+ plan: "premium",+ signupDate: "2026-01-14",+});+```++Traits are free-form β any key / value pair you find useful. They're+merged per key across calls, so a later `identify()` (or+[`setTraits()`](/swetrix-js-reference#settraits)) only overwrites the+keys it carries, and passing `null` removes one:++```javascript+// Later, without repeating the user ID+swetrix.setTraits({ plan: "enterprise", trialEndsAt: null });+```++The limits per call: up to 50 keys, keys of up to 128 characters, and+2000 characters for all keys and values combined. Values must be+strings, numbers, booleans or `null`, and are stored as strings.++<Callout type="warn">+ Traits are the one place where personal data legitimately ends up in Swetrix β an email address on+ a profile is exactly what the feature is for. Send only what you actually need, and make sure your+ privacy policy covers it.</Callout>### Notes on consentdiff --git a/packages/tracker-js/README.md b/packages/tracker-js/README.mdindex f89d951e2..d825fbaf8 100644--- a/packages/tracker-js/README.md+++ b/packages/tracker-js/README.md@@ -260,7 +260,7 @@ await startSessionReplay({})```-### `identify(profileId)` / `reset()`+### `identify(profileId, traits?)` / `setTraits(traits)` / `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.@@ -272,7 +272,18 @@ identify('user-12345')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.+Use a unique, stable identifier (e.g. an internal user ID). The ID is stored as provided and shown in your dashboard, so don't pass values you wouldn't want to see there. Swetrix stores nothing in the browser, so call `identify()` on every page load while the user is logged in.++Optionally pass **traits** β key / value metadata displayed on the user's profile:++```javascript+identify('user-12345', { email: '[email protected]', plan: 'premium' })++// Later, without repeating the user ID. null removes a trait+setTraits({ plan: 'enterprise', trialEndsAt: null })+```++Traits are merged per key. Per call: max 50 keys, 128 characters per key, and 2000 characters for all keys and values combined.### Session & Profile IDsdiff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.tsindex 195277bec..dc78d0f1f 100644--- a/packages/tracker-js/src/Lib.ts+++ b/packages/tracker-js/src/Lib.ts@@ -46,6 +46,12 @@ declare global {}}+/**+ * Key / value metadata describing an identified user (email, plan, signup+ * date, ...). Values are stored as strings; `null` removes a trait.+ */+export type Traits = Record<string, string | number | boolean | null>+export interface LibOptions {/*** When set to `true`, localhost events will be sent to server.@@ -661,10 +667,13 @@ export class Lib {* 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.+ * user ID. It's stored as you provide it, so don't pass values you wouldn't+ * want to see in your dashboard.+ * @param traits Optional key / value metadata to show on the user's profile,+ * e.g. their email, plan or signup date. Traits are merged with the ones+ * already stored; pass `null` to remove one.*/- async identify(profileId: string): Promise<void> {+ async identify(profileId: string, traits?: Traits): Promise<void> {if (typeof profileId !== 'string' || !profileId.trim()) {console.error('[Swetrix] identify() expects a non-empty string profileId')return@@ -677,11 +686,14 @@ export class Lib {profileId: trimmed,}- if (!this.canTrack() || this.lastIdentifySent === trimmed) {+ // Traits are part of the payload, so re-send when only they changed+ const identifyKey = `${trimmed}:${traits ? JSON.stringify(traits) : ''}`++ if (!this.canTrack() || this.lastIdentifySent === identifyKey) {return}- this.lastIdentifySent = trimmed+ this.lastIdentifySent = identifyKey// The profile changed, so cached flags / experiments may no longer applythis.clearFeatureFlagsCache()@@ -693,7 +705,7 @@ export class Lib {headers: {'Content-Type': 'application/json',},- body: JSON.stringify({ pid: this.projectID, profileId: trimmed }),+ body: JSON.stringify({ pid: this.projectID, profileId: trimmed, traits }),})if (!response.ok) {@@ -708,6 +720,27 @@ export class Lib {}}+ /**+ * Updates the traits of the already identified visitor without having to+ * repeat their user ID. Only the keys you pass are touched; pass `null` to+ * remove a trait.+ */+ async setTraits(traits: Traits): Promise<void> {+ const profileId = this.options?.profileId++ if (!profileId) {+ console.error('[Swetrix] setTraits() requires the visitor to be identified via identify() first')+ return+ }++ if (!traits || typeof traits !== 'object' || Array.isArray(traits)) {+ console.error('[Swetrix] setTraits() expects an object of traits')+ return+ }++ await this.identify(profileId, traits)+ }+/*** Resets the visitor's identity set via identify() (e.g. after they log* out), so subsequent events are tracked anonymously again. Important ondiff --git a/packages/tracker-js/src/index.ts b/packages/tracker-js/src/index.tsindex 35ef87577..3802eb611 100644--- a/packages/tracker-js/src/index.ts+++ b/packages/tracker-js/src/index.ts@@ -14,6 +14,7 @@ import {SessionReplayOptions,SessionReplayActions,defaultSessionReplayActions,+ Traits,} from './Lib.js'export let LIB_INSTANCE: Lib | null = null@@ -289,22 +290,44 @@ export function clearExperimentsCache(): void {* 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.+ * user ID. It's stored as you provide it, so don't pass values you wouldn't+ * want to see in your dashboard.+ * @param traits Optional key / value metadata to show on the user's profile,+ * e.g. their email, plan or signup date. Traits are merged with the ones+ * already stored; pass `null` to remove one.** @example* ```typescript* // After the user logs in (or on page load if they're already logged in)- * swetrix.identify('user-12345')+ * swetrix.identify('user-12345', {+ * email: '[email protected]',+ * plan: 'premium',+ * })** // On logout* swetrix.reset()* ```*/-export async function identify(profileId: string): Promise<void> {+export async function identify(profileId: string, traits?: Traits): Promise<void> {+ if (!LIB_INSTANCE) return++ await LIB_INSTANCE.identify(profileId, traits)+}++/**+ * Updates the traits of the already identified visitor without having to+ * repeat their user ID. Only the keys you pass are touched; pass `null` to+ * remove a trait.+ *+ * @example+ * ```typescript+ * swetrix.setTraits({ plan: 'enterprise', trialEndsAt: null })+ * ```+ */+export async function setTraits(traits: Traits): Promise<void> {if (!LIB_INSTANCE) return- await LIB_INSTANCE.identify(profileId)+ await LIB_INSTANCE.setTraits(traits)}/**@@ -387,4 +410,5 @@ export {IPageViewPayload,FeatureFlagsOptions,ExperimentOptions,+ Traits,}diff --git a/packages/tracker-node/README.md b/packages/tracker-node/README.mdindex 900907d8e..e83de2780 100644--- a/packages/tracker-node/README.md+++ b/packages/tracker-node/README.md@@ -441,7 +441,18 @@ Link a visitor's anonymous profile to your own user ID (e.g. after they log in),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.+Use a unique, stable identifier (e.g. an internal user ID). The ID is stored as provided and shown in your dashboard, so don't pass values you wouldn't want to see there.++You can also pass **traits** β key / value metadata displayed on the user's profile. Traits are merged per key, and `null` removes one:++```javascript+await swetrix.identify('192.155.52.12', 'Mozilla/5.0...', 'user-12345', {+ email: '[email protected]',+ plan: 'premium',+})+```++Per call: max 50 keys, 128 characters per key, and 2000 characters for all keys and values combined.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.diff --git a/packages/tracker-node/src/index.ts b/packages/tracker-node/src/index.tsindex 760a3092d..30ead6f14 100644--- a/packages/tracker-node/src/index.ts+++ b/packages/tracker-node/src/index.ts@@ -223,6 +223,12 @@ export interface ExperimentOptions {profileId?: string}+/**+ * Key / value metadata describing an identified user (email, plan, signup+ * date, ...). Values are stored as strings; `null` removes a trait.+ */+export type Traits = Record<string, string | number | boolean | null>+const DEFAULT_API_HOST = 'https://api.swetrix.com/log'const DEFAULT_API_BASE = 'https://api.swetrix.com'@@ -572,12 +578,15 @@ export class Swetrix {* @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.+ * user ID. It's stored as you provide it, so don't pass values you wouldn't+ * want to see in your dashboard.+ * @param traits Optional key / value metadata to show on the user's profile,+ * e.g. their email, plan or signup date. Traits are merged with the ones+ * already stored; pass `null` to remove one.* @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> {+ public async identify(ip: string, userAgent: string, profileId: string, traits?: Traits): Promise<string | null> {if (!this.canTrack()) {return null}@@ -596,7 +605,7 @@ export class Swetrix {'X-Client-IP-Address': ip,'User-Agent': userAgent,},- body: JSON.stringify({ pid: this.projectID, profileId: profileId.trim() }),+ body: JSON.stringify({ pid: this.projectID, profileId: profileId.trim(), traits }),})if (!response.ok) {diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex 305e6459a..cd793300d 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -150,6 +150,7 @@ export interface Profile {export interface ProfileDetails extends Profile {avgDuration: number+ traits?: Record<string, string>region: string | nullcity: string | nulllocale: string | nulldiff --git a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsxindex 23b0dce53..802c66233 100644--- a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx+++ b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx@@ -609,6 +609,11 @@ export const ProfileDetails = ({[details?.lastSeen],)+ const traits = useMemo(+ () => Object.entries(details?.traits || {}),+ [details?.traits],+ )+if (!details) return <Loader />const avgDurationStr = details.avgDuration@@ -983,6 +988,20 @@ export const ProfileDetails = ({</div></PanelSection>+ {_isEmpty(traits) ? null : (+ <PanelSection title={t('project.userTraits')}>+ <div>+ {traits.map(([key, value]) => (+ <InfoRow+ key={key}+ label={key}+ value={<span title={value}>{value}</span>}+ />+ ))}+ </div>+ </PanelSection>+ )}+<PanelSection title={t('project.locationAndDevice')}><div><InfoRowdiff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 8ef647a1a..606c43a53 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1965,6 +1965,7 @@},"pageflow": "Page flow","userSessions": "Sessions",+ "userTraits": "User traits","noSessions": "No sessions found for this user.","unknown": "Unknown","backToErrors": "Back to errors list",