π 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
Prefix profile IDs with usr_
Blue Mouseca22c750a2c1
diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdxindex faf4d5272..850fba364 100644--- a/docs/content/docs/script-reference.mdx+++ b/docs/content/docs/script-reference.mdx@@ -514,7 +514,13 @@ swetrix.clearExperimentsCache();## getProfileId()-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.+Gets the profile ID the current visitor's events are stored under. If the visitor was identified via [identify()](#identify), or a `profileId` was set via `init`, returns the identified (`usr_`-prefixed) profile ID. Otherwise, requests server to generate an anonymous (`anon_`-prefixed) one from IP/UA hash.++<Callout type="info">+ The prefix matters: your own user ID is stored behind `usr_`, so a raw `user-12345` won't match+ anything in the dashboard. Always attribute revenue with the value `getProfileId()` returns rather+ than the ID you passed to `init()` / `identify()`.+</Callout>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/packages/tracker-js/README.md b/packages/tracker-js/README.mdindex 971ff5a83..edfda43c0 100644--- a/packages/tracker-js/README.md+++ b/packages/tracker-js/README.md@@ -294,6 +294,8 @@ const sessionId = await getSessionId()These are useful for revenue attribution with payment providers like Paddle.+`getProfileId()` returns the ID the visitor's events are actually stored under β `usr_`-prefixed once they're identified (via `identify()` or a `profileId` on `init()`), `anon_`-prefixed otherwise. Attribute revenue with this value, not the raw ID you passed in.+## Self-HostingIf you're running a self-hosted [Swetrix API](https://github.com/Swetrix/swetrix-api) instance, point the `apiURL` to your server:diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.tsindex 9ff6780f8..354370c2f 100644--- a/packages/tracker-js/src/Lib.ts+++ b/packages/tracker-js/src/Lib.ts@@ -310,6 +310,16 @@ export const defaultSessionReplayActions: SessionReplayActions = {const DEFAULT_API_HOST = 'https://api.swetrix.com/log'const DEFAULT_API_BASE = 'https://api.swetrix.com'++/**+ * Events carry the raw, site-supplied profileId; the server stores them behind+ * this prefix. Mirrored here so getProfileId() can report the ID events are+ * actually stored under without an extra round trip.+ */+const USER_PROFILE_PREFIX = 'usr_'++const toStoredProfileId = (profileId: string) => `${USER_PROFILE_PREFIX}${profileId.trim()}`+const DEFAULT_RRWEB_FILE = 'replaylibrary.min.js'const DEFAULT_RRWEB_URL = `https://cdn.jsdelivr.net/npm/swetrix@latest/dist/${DEFAULT_RRWEB_FILE}`const DEFAULT_SESSION_REPLAY_FLUSH_INTERVAL = 5000@@ -851,9 +861,10 @@ export class Lib {}/**- * Gets the anonymous profile ID for the current visitor.- * If profileId was set via init options, returns that.- * Otherwise, requests server to generate one from IP/UA hash.+ * Gets the profile ID the current visitor's events are stored under.+ * If the visitor was identified via identify(), or a profileId was set via+ * init options, returns the identified (usr_-prefixed) ID. Otherwise,+ * requests server to generate an anonymous one from IP/UA hash.** This ID can be used for revenue attribution with payment providers.*@@ -880,9 +891,11 @@ export class Lib {return this.identifiedProfileId}- // If profileId is already set in options, return it+ // A profileId set via init() (or a failed identify() call) is sent raw on+ // events and prefixed server-side, so return the prefixed form here too -+ // returning the raw value would not match anything in the dashboardif (this.options?.profileId) {- return this.options.profileId+ return toStoredProfileId(this.options.profileId)}if (!isInBrowser()) {diff --git a/packages/tracker-js/tests/identify.test.ts b/packages/tracker-js/tests/identify.test.tsnew file mode 100644index 000000000..3819f6192--- /dev/null+++ b/packages/tracker-js/tests/identify.test.ts@@ -0,0 +1,146 @@+import { setLocation } from './testUtils'++// Mock fetch globally+const mockFetch = jest.fn()+global.fetch = mockFetch++describe('Visitor identification', () => {+ const PROJECT_ID = 'test-project-id'++ beforeEach(() => {+ jest.clearAllMocks()+ jest.resetModules()+ mockFetch.mockReset()++ setLocation({ hostname: 'example.com', pathname: '/test-page' })+ })++ const lastRequestBody = () => JSON.parse(mockFetch.mock.calls[0][1].body)++ describe('identify', () => {+ test('should send the profileId as provided, without hashing it', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => ({ profileId: 'usr_user-12345' }),+ })++ const { init, identify } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })+ await identify('user-12345')++ expect(mockFetch).toHaveBeenCalledWith(expect.stringContaining('/log/identify'), expect.anything())+ expect(lastRequestBody()).toEqual({+ pid: PROJECT_ID,+ profileId: 'user-12345',+ })+ })++ test('should send traits alongside the profileId', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => ({ profileId: 'usr_user-12345' }),+ })++ const { init, identify } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })+ await identify('user-12345', { email: '[email protected]', plan: 'premium' })++ expect(lastRequestBody().traits).toEqual({+ email: '[email protected]',+ plan: 'premium',+ })+ })++ test('should deduplicate repeated calls but re-send when traits change', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ json: async () => ({ profileId: 'usr_user-12345' }),+ })++ const { init, identify } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })++ await identify('user-12345', { plan: 'free' })+ await identify('user-12345', { plan: 'free' })+ expect(mockFetch).toHaveBeenCalledTimes(1)++ await identify('user-12345', { plan: 'premium' })+ expect(mockFetch).toHaveBeenCalledTimes(2)+ })++ test('setTraits should reuse the identified profileId', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ json: async () => ({ profileId: 'usr_user-12345' }),+ })++ const { init, identify, setTraits } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })++ await identify('user-12345')+ await setTraits({ plan: 'enterprise', trialEndsAt: null })++ const body = JSON.parse(mockFetch.mock.calls[1][1].body)+ expect(body.profileId).toBe('user-12345')+ expect(body.traits).toEqual({ plan: 'enterprise', trialEndsAt: null })+ })++ test('setTraits should be a no-op when the visitor was never identified', async () => {+ const { init, setTraits } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })++ await setTraits({ plan: 'enterprise' })++ expect(mockFetch).not.toHaveBeenCalled()+ })+ })++ describe('getProfileId', () => {+ test('should return the identified profileId returned by the API', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => ({ profileId: 'usr_user-12345' }),+ })++ const { init, identify, getProfileId } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })+ await identify('user-12345')++ await expect(getProfileId()).resolves.toBe('usr_user-12345')+ })++ // Events carry the raw profileId and the server prefixes it, so the raw+ // value would not match anything in the dashboard (breaking revenue+ // attribution for sites that set profileId without calling identify()).+ test('should prefix a profileId set via init, matching how events are stored', async () => {+ const { init, getProfileId } = await import('../src/index')+ init(PROJECT_ID, { devMode: true, profileId: 'user-12345' })++ await expect(getProfileId()).resolves.toBe('usr_user-12345')+ expect(mockFetch).not.toHaveBeenCalled()+ })++ test('should prefix the profileId even when the identify request failed', async () => {+ mockFetch.mockResolvedValueOnce({ ok: false })++ const { init, identify, getProfileId } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })+ await identify('user-12345')++ await expect(getProfileId()).resolves.toBe('usr_user-12345')+ })++ test('should request an anonymous profileId when the visitor is not identified', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => ({ profileId: 'anon_8214637194021987452' }),+ })++ const { init, getProfileId } = await import('../src/index')+ init(PROJECT_ID, { devMode: true })++ await expect(getProfileId()).resolves.toBe('anon_8214637194021987452')+ expect(mockFetch).toHaveBeenCalledWith(expect.stringContaining('/log/profile-id'), expect.anything())+ })+ })+})diff --git a/packages/tracker-node/README.md b/packages/tracker-node/README.mdindex 8d47ec742..1e9946087 100644--- a/packages/tracker-node/README.md+++ b/packages/tracker-node/README.md@@ -431,7 +431,7 @@ const profileId = await swetrix.getProfileId('192.155.52.12', 'Mozilla/5.0...')// e.g., Paddle Checkout customData: { swetrix_profile_id: profileId }```-If you set a `profileId` in the constructor options, it will be returned directly instead of generating one.+If you set a `profileId` in the constructor options, its identified form (`usr_`-prefixed, the way events are stored) is returned instead of generating an anonymous one. Always attribute revenue with the value this returns, not the raw ID you passed in.## Identifying usersdiff --git a/packages/tracker-node/package.json b/packages/tracker-node/package.jsonindex d535fd9eb..4667312c5 100644--- a/packages/tracker-node/package.json+++ b/packages/tracker-node/package.json@@ -1,6 +1,6 @@{"name": "@swetrix/node",- "version": "3.3.0",+ "version": "3.3.1","description": "Swetrix NodeJS server-side tracking module","keywords": ["analytics",diff --git a/packages/tracker-node/src/index.ts b/packages/tracker-node/src/index.tsindex 244cc4bbe..8aacc3914 100644--- a/packages/tracker-node/src/index.ts+++ b/packages/tracker-node/src/index.ts@@ -232,6 +232,15 @@ 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'+/**+ * Events carry the raw, site-supplied profileId; the server stores them behind+ * this prefix. Mirrored here so getProfileId() can report the ID events are+ * actually stored under without an extra round trip.+ */+const USER_PROFILE_PREFIX = 'usr_'++const toStoredProfileId = (profileId: string) => `${USER_PROFILE_PREFIX}${profileId.trim()}`+/*** Server-side implementation of Swetrix tracking library.*@@ -472,9 +481,10 @@ export class Swetrix {}/**- * Gets the anonymous profile ID for a visitor.- * If profileId was set via constructor options, returns that.- * Otherwise, requests server to generate one from IP/UA hash.+ * Gets the profile ID a visitor's events are stored under.+ * If profileId was set via constructor options, returns the identified+ * (usr_-prefixed) form of it. Otherwise, requests server to generate an+ * anonymous one from IP/UA hash.** This ID can be used for revenue attribution with payment providers like Paddle.*@@ -491,9 +501,11 @@ export class Swetrix {* ```*/public async getProfileId(ip: string, userAgent: string): Promise<string | null> {- // If profileId is already set in options, return it+ // A profileId set via the constructor is sent raw on events and prefixed+ // server-side, so return the prefixed form here too - returning the raw+ // value would not match anything in the dashboardif (this.options?.profileId) {- return this.options.profileId+ return toStoredProfileId(this.options.profileId)}try {