From 9815acfc4c939e9d10d8d617d44e950a88774086 Mon Sep 17 00:00:00 2001 From: Kiran K Date: Mon, 16 Nov 2026 16:50:51 +0530 Subject: [PATCH 1/6] Start the Fingerprint agent when identity-agent.js loads --- packages/script/src/identity-agent.js | 15 +++++++++----- packages/script/src/identity-agent.test.js | 24 ++++++++++++++++++---- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/packages/script/src/identity-agent.js b/packages/script/src/identity-agent.js index d6810ad..1014fc3 100644 --- a/packages/script/src/identity-agent.js +++ b/packages/script/src/identity-agent.js @@ -4,17 +4,22 @@ const FINGERPRINT_PUBLIC_KEY = process.env.DUB_FINGERPRINT_PUBLIC_KEY; // Dub's Fingerprint custom subdomain, so ad blockers don't stop the agent; Fingerprint's default stays as the fallback const FINGERPRINT_ENDPOINTS = ['https://identity.dub.co']; +// Started on load so browser signals are collected before identify() asks for the visitorId +const agent = FINGERPRINT_PUBLIC_KEY + ? start({ + apiKey: FINGERPRINT_PUBLIC_KEY, + endpoints: FINGERPRINT_ENDPOINTS, + }) + : null; + // Loaded on demand by the identity extension; resolves the visitorId once Dub has accepted or rejected the identification async function identify({ apiHost, clickId }) { - if (!FINGERPRINT_PUBLIC_KEY) { + if (!agent) { return null; } // Needs Sealed Client Results off for the workspace, so visitor_id comes back in plaintext - const { visitor_id: visitorId, event_id: eventId } = await start({ - apiKey: FINGERPRINT_PUBLIC_KEY, - endpoints: FINGERPRINT_ENDPOINTS, - }).get({ + const { visitor_id: visitorId, event_id: eventId } = await agent.get({ linkedId: clickId, }); diff --git a/packages/script/src/identity-agent.test.js b/packages/script/src/identity-agent.test.js index 5882c26..0ad15c1 100644 --- a/packages/script/src/identity-agent.test.js +++ b/packages/script/src/identity-agent.test.js @@ -21,6 +21,7 @@ vi.mock('@fingerprint/agent', () => ({ })); const fetchMock = vi.fn(); +const startCallsOnLoad = [...start.mock.calls]; function identify() { return window._dubIdentity.identify({ @@ -54,13 +55,28 @@ describe('identity-agent.js', () => { vi.clearAllMocks(); }); + it('starts the agent once when the file loads', async () => { + expect(startCallsOnLoad).toEqual([ + [ + { + apiKey: 'test_public_key', + endpoints: ['https://identity.dub.co'], + }, + ], + ]); + + const startCalls = start.mock.calls.length; + + await identify(); + await identify(); + + expect(start).toHaveBeenCalledTimes(startCalls); + expect(get).toHaveBeenCalledTimes(2); + }); + it('identifies with linkedId set to the clickId and posts only the eventId', async () => { await expect(identify()).resolves.toBe(VISITOR_ID); - expect(start).toHaveBeenCalledWith({ - apiKey: 'test_public_key', - endpoints: ['https://identity.dub.co'], - }); expect(get).toHaveBeenCalledWith({ linkedId: CLICK_ID, }); From b489bc09e676b6c486315e8b9ff4da03c8f6a543 Mon Sep 17 00:00:00 2001 From: Kiran K Date: Mon, 16 Nov 2026 16:50:52 +0530 Subject: [PATCH 2/6] Preload identity-agent.js for an unidentified partner click --- packages/script/src/extensions/identity.js | 25 +++++++++-- .../script/src/extensions/identity.test.js | 44 +++++++++++++++++-- 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/packages/script/src/extensions/identity.js b/packages/script/src/extensions/identity.js index a1cdf66..ca18de2 100644 --- a/packages/script/src/extensions/identity.js +++ b/packages/script/src/extensions/identity.js @@ -108,19 +108,36 @@ const initIdentity = () => { } } - // Links the visitor's device to their click once, then suffixes dub_id with the visitorId - async function identifyClick() { + async function getUnidentifiedPartnerClickId() { await getPendingClick().catch(() => undefined); const clickId = cookieManager.get(DUB_ID_VAR); // Click ids never contain "_", so a suffixed dub_id is already identified if (!clickId || clickId.includes('_')) { - return; + return undefined; } // Fingerprint is only for partner clicks, so skip ad and site-visit clicks, and clicks newer than the partner data if (getPartnerClickId() !== clickId) { + return undefined; + } + + return clickId; + } + + // Loading the agent early lets Fingerprint collect signals before trackIdentity() needs the visitorId + async function preloadIdentityAgent() { + if (await getUnidentifiedPartnerClickId()) { + await loadIdentityAgent(); + } + } + + // Links the visitor's device to their click once, then suffixes dub_id with the visitorId + async function identifyClick() { + const clickId = await getUnidentifiedPartnerClickId(); + + if (!clickId) { return; } @@ -211,6 +228,8 @@ const initIdentity = () => { queueManager.queue = remainingQueue; } + preloadIdentityAgent().catch(() => undefined); + watchIdentityPaths(); }; diff --git a/packages/script/src/extensions/identity.test.js b/packages/script/src/extensions/identity.test.js index a13c754..0fbfebc 100644 --- a/packages/script/src/extensions/identity.test.js +++ b/packages/script/src/extensions/identity.test.js @@ -179,7 +179,7 @@ describe('identity extension', () => { }); await flush(); - expect(loadedIdentityScripts()).toEqual([]); + expect(identify).not.toHaveBeenCalled(); }); it('is not part of variants without the identity extension', async () => { @@ -198,13 +198,49 @@ describe('identity extension', () => { expect(loadedIdentityScripts()).toEqual([]); }); - it('does nothing without data-track-identity-paths', async () => { + it('preloads identity-agent.js for an unidentified partner click without identifying it', async () => { setPartnerClick(); runScript(); + + await vi.waitFor(() => { + expect(loadedIdentityScripts()).toEqual([ + 'https://www.dubcdn.com/analytics/identity-agent.js', + ]); + }); await flush(); - expect(loadedIdentityScripts()).toEqual([]); + expect(identify).not.toHaveBeenCalled(); + expect(getCookie('dub_id')).toBe(CLICK_ID); + }); + + it('reuses the preloaded identity-agent.js when identifying', async () => { + setPartnerClick(); + + runScript(); + await vi.waitFor(() => { + expect(loadedIdentityScripts()).toHaveLength(1); + }); + + await window.dubAnalytics.trackIdentity(); + + expect(identify).toHaveBeenCalledTimes(1); + expect(loadedIdentityScripts()).toHaveLength(1); + }); + + it('never throws when the identity-agent.js preload fails', async () => { + document.head.appendChild.mockImplementation((node) => { + document.head.append(node); + setTimeout(() => node.onerror()); + return node; + }); + setPartnerClick(); + + expect(() => runScript()).not.toThrow(); + await flush(); + await flush(); + + expect(console.warn).not.toHaveBeenCalled(); }); it('ignores data-track-identity-paths that is not an array of paths', async () => { @@ -424,7 +460,7 @@ describe('identity extension', () => { }); await flush(); - expect(loadedIdentityScripts()).toEqual([]); + expect(identify).not.toHaveBeenCalled(); window.history.pushState(null, '', '/signup'); From 32b69f733ed77eb09e990a68654cd1981f225bc3 Mon Sep 17 00:00:00 2001 From: Kiran K Date: Mon, 16 Nov 2026 17:06:00 +0530 Subject: [PATCH 3/6] Add an identity demo page to the Next.js example --- apps/nextjs/README.md | 10 +- apps/nextjs/app/identity/[[...slug]]/route.ts | 99 +++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 apps/nextjs/app/identity/[[...slug]]/route.ts diff --git a/apps/nextjs/README.md b/apps/nextjs/README.md index 7ddd0dd..d05ee65 100644 --- a/apps/nextjs/README.md +++ b/apps/nextjs/README.md @@ -18,4 +18,12 @@ export default function RootLayout({ ); } -``` \ No newline at end of file +``` +## Identity demo + +`/identity` and `/identity/signup` load the `script.identity.js` build next to `DUB_ANALYTICS_SCRIPT_URL`, with `/identity/signup` as the only identity path. Each page shows the `dub_id` cookies and when the Fingerprint agent and `/track/identity` requests ran. + +1. Build the script with a Fingerprint key: `DUB_FINGERPRINT_PUBLIC_KEY= pnpm --filter @dub/analytics-script build`. +2. Serve it: `cd packages/script/dist && python3 -m http.server 4000`. +3. Start the app with `DUB_ANALYTICS_SCRIPT_URL=http://localhost:4000/analytics/script.js`. Set `DUB_IDENTITY_API_HOST` (e.g. `http://localhost:8888/api`) and `DUB_IDENTITY_REFER_DOMAIN` for a local Dub app. +4. Open `/identity?via=`, then `/identity/signup`. diff --git a/apps/nextjs/app/identity/[[...slug]]/route.ts b/apps/nextjs/app/identity/[[...slug]]/route.ts new file mode 100644 index 0000000..c388a4d --- /dev/null +++ b/apps/nextjs/app/identity/[[...slug]]/route.ts @@ -0,0 +1,99 @@ +import { DUB_ANALYTICS_SCRIPT_URL } from '@/app/constants'; + +const IDENTITY_SCRIPT_URL = DUB_ANALYTICS_SCRIPT_URL.replace( + /script[^/]*\.js$/, + 'script.identity.js', +); +const REFER_DOMAIN = process.env.DUB_IDENTITY_REFER_DOMAIN || 'getacme.link'; +const API_HOST = process.env.DUB_IDENTITY_API_HOST || ''; +const IDENTITY_PATH = '/identity/signup'; + +// A plain HTML page, outside the root layout, so only the identity variant of the local build loads +function renderPage(pathname: string) { + const isIdentityPath = pathname === IDENTITY_PATH; + const apiHostAttribute = API_HOST ? `data-api-host="${API_HOST}"` : ''; + + return ` + + + + Identity demo + + + + + +

Identity demo

+

+ ${ + isIdentityPath + ? `${IDENTITY_PATH} is an identity path, so a partner click is identified on load.` + : `Not an identity path, so a partner click only preloads the Fingerprint agent here.` + } +

+

+ Home · Sign up · + +

+

Cookies

+

+    

Identity requests (ms after page start)

+

+    
+  
+`;
+}
+
+export function GET(request: Request) {
+  return new Response(renderPage(new URL(request.url).pathname), {
+    headers: {
+      'Content-Type': 'text/html; charset=utf-8',
+    },
+  });
+}

From a35d9ffa65965f7fc01e32fbb4e518853b8ff577 Mon Sep 17 00:00:00 2001
From: Kiran K 
Date: Mon, 16 Nov 2026 17:06:00 +0530
Subject: [PATCH 4/6] Cover the identity agent preload in Playwright

---
 apps/nextjs/tests/identity.spec.ts | 66 +++++++++++++++++++++++++-----
 1 file changed, 55 insertions(+), 11 deletions(-)

diff --git a/apps/nextjs/tests/identity.spec.ts b/apps/nextjs/tests/identity.spec.ts
index 71e2fb2..97b1127 100644
--- a/apps/nextjs/tests/identity.spec.ts
+++ b/apps/nextjs/tests/identity.spec.ts
@@ -54,13 +54,35 @@ async function stubIdentityAgent(page: Page) {
 
     return route.fulfill({
       contentType: 'application/javascript',
-      body: `window._dubIdentity = { identify: async () => '${VISITOR_ID}' };`,
+      body: `window._dubIdentity = {
+        identify: async () => {
+          window.identifyCalls = (window.identifyCalls || 0) + 1;
+          return '${VISITOR_ID}';
+        },
+      };`,
     });
   });
 
   return agentRequests;
 }
 
+function mockPartnerClick(page: Page) {
+  return page.route('**/track/click', (route) =>
+    route.fulfill({
+      contentType: 'application/json',
+      body: JSON.stringify({
+        clickId: CLICK_ID,
+        partner: { id: 'pn_e2e', name: 'Partner', image: null },
+        discount: null,
+      }),
+    }),
+  );
+}
+
+function getIdentifyCalls(page: Page) {
+  return page.evaluate(() => (window as any).identifyCalls ?? 0);
+}
+
 async function getDubId(page: Page) {
   const cookies = await page.context().cookies(SITE);
 
@@ -74,16 +96,7 @@ test.describe('Identity tracking', () => {
     await serveSite(page);
     const agentRequests = await stubIdentityAgent(page);
 
-    await page.route('**/track/click', (route) =>
-      route.fulfill({
-        contentType: 'application/json',
-        body: JSON.stringify({
-          clickId: CLICK_ID,
-          partner: { id: 'pn_e2e', name: 'Partner', image: null },
-          discount: null,
-        }),
-      }),
-    );
+    await mockPartnerClick(page);
 
     await page.goto(`${SITE}/signup?via=partner`);
 
@@ -105,4 +118,35 @@ test.describe('Identity tracking', () => {
     expect(agentRequests).toHaveLength(0);
     expect(await getDubId(page)).toBe(CLICK_ID);
   });
+
+  test('preloads the agent for a partner click outside an identity path, without identifying it', async ({
+    page,
+  }) => {
+    await serveSite(page);
+    const agentRequests = await stubIdentityAgent(page);
+    await mockPartnerClick(page);
+
+    await page.goto(`${SITE}/pricing?via=partner`);
+
+    await expect.poll(() => agentRequests.length).toBe(1);
+    await expect.poll(() => getDubId(page)).toBe(CLICK_ID);
+    expect(await getIdentifyCalls(page)).toBe(0);
+  });
+
+  test('reuses the preloaded agent when trackIdentity() runs', async ({
+    page,
+  }) => {
+    await serveSite(page);
+    const agentRequests = await stubIdentityAgent(page);
+    await mockPartnerClick(page);
+
+    await page.goto(`${SITE}/pricing?via=partner`);
+    await expect.poll(() => agentRequests.length).toBe(1);
+
+    await page.evaluate(() => (window as any).dubAnalytics.trackIdentity());
+
+    expect(await getDubId(page)).toBe(`${CLICK_ID}_${VISITOR_ID}`);
+    expect(await getIdentifyCalls(page)).toBe(1);
+    expect(agentRequests).toHaveLength(1);
+  });
 });

From 584927a7574fe0cd23814602a2c10caacb3204ab Mon Sep 17 00:00:00 2001
From: Kiran K 
Date: Mon, 16 Nov 2026 17:26:44 +0530
Subject: [PATCH 5/6] Keep a malformed cookie from breaking the identity demo
 panels

---
 apps/nextjs/app/identity/[[...slug]]/route.ts | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/apps/nextjs/app/identity/[[...slug]]/route.ts b/apps/nextjs/app/identity/[[...slug]]/route.ts
index c388a4d..d6ac198 100644
--- a/apps/nextjs/app/identity/[[...slug]]/route.ts
+++ b/apps/nextjs/app/identity/[[...slug]]/route.ts
@@ -61,7 +61,11 @@ function renderPage(pathname: string) {
         var cookies = Object.fromEntries(
           document.cookie.split(';').filter(Boolean).map(function (c) {
             var i = c.indexOf('=');
-            return [c.slice(0, i).trim(), decodeURIComponent(c.slice(i + 1))];
+            var value = c.slice(i + 1);
+            try {
+              value = decodeURIComponent(value);
+            } catch (error) {}
+            return [c.slice(0, i).trim(), value];
           }),
         );
         document.getElementById('cookies').textContent = JSON.stringify(

From ec72146a34916d9a451cee108791af849b51afa8 Mon Sep 17 00:00:00 2001
From: Kiran K 
Date: Mon, 16 Nov 2026 18:03:17 +0530
Subject: [PATCH 6/6] Remove the identity demo page and Playwright changes from
 the Next.js example

---
 apps/nextjs/README.md                         |  10 +-
 apps/nextjs/app/identity/[[...slug]]/route.ts | 103 ------------------
 apps/nextjs/tests/identity.spec.ts            |  66 ++---------
 3 files changed, 12 insertions(+), 167 deletions(-)
 delete mode 100644 apps/nextjs/app/identity/[[...slug]]/route.ts

diff --git a/apps/nextjs/README.md b/apps/nextjs/README.md
index d05ee65..7ddd0dd 100644
--- a/apps/nextjs/README.md
+++ b/apps/nextjs/README.md
@@ -18,12 +18,4 @@ export default function RootLayout({
     
   );
 }
-```
-## Identity demo
-
-`/identity` and `/identity/signup` load the `script.identity.js` build next to `DUB_ANALYTICS_SCRIPT_URL`, with `/identity/signup` as the only identity path. Each page shows the `dub_id` cookies and when the Fingerprint agent and `/track/identity` requests ran.
-
-1. Build the script with a Fingerprint key: `DUB_FINGERPRINT_PUBLIC_KEY= pnpm --filter @dub/analytics-script build`.
-2. Serve it: `cd packages/script/dist && python3 -m http.server 4000`.
-3. Start the app with `DUB_ANALYTICS_SCRIPT_URL=http://localhost:4000/analytics/script.js`. Set `DUB_IDENTITY_API_HOST` (e.g. `http://localhost:8888/api`) and `DUB_IDENTITY_REFER_DOMAIN` for a local Dub app.
-4. Open `/identity?via=`, then `/identity/signup`.
+```
\ No newline at end of file
diff --git a/apps/nextjs/app/identity/[[...slug]]/route.ts b/apps/nextjs/app/identity/[[...slug]]/route.ts
deleted file mode 100644
index d6ac198..0000000
--- a/apps/nextjs/app/identity/[[...slug]]/route.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { DUB_ANALYTICS_SCRIPT_URL } from '@/app/constants';
-
-const IDENTITY_SCRIPT_URL = DUB_ANALYTICS_SCRIPT_URL.replace(
-  /script[^/]*\.js$/,
-  'script.identity.js',
-);
-const REFER_DOMAIN = process.env.DUB_IDENTITY_REFER_DOMAIN || 'getacme.link';
-const API_HOST = process.env.DUB_IDENTITY_API_HOST || '';
-const IDENTITY_PATH = '/identity/signup';
-
-// A plain HTML page, outside the root layout, so only the identity variant of the local build loads
-function renderPage(pathname: string) {
-  const isIdentityPath = pathname === IDENTITY_PATH;
-  const apiHostAttribute = API_HOST ? `data-api-host="${API_HOST}"` : '';
-
-  return `
-
-  
-    
-    Identity demo
-    
-    
-    
-  
-  
-    

Identity demo

-

- ${ - isIdentityPath - ? `${IDENTITY_PATH} is an identity path, so a partner click is identified on load.` - : `Not an identity path, so a partner click only preloads the Fingerprint agent here.` - } -

-

- Home · Sign up · - -

-

Cookies

-

-    

Identity requests (ms after page start)

-

-    
-  
-`;
-}
-
-export function GET(request: Request) {
-  return new Response(renderPage(new URL(request.url).pathname), {
-    headers: {
-      'Content-Type': 'text/html; charset=utf-8',
-    },
-  });
-}
diff --git a/apps/nextjs/tests/identity.spec.ts b/apps/nextjs/tests/identity.spec.ts
index 97b1127..71e2fb2 100644
--- a/apps/nextjs/tests/identity.spec.ts
+++ b/apps/nextjs/tests/identity.spec.ts
@@ -54,35 +54,13 @@ async function stubIdentityAgent(page: Page) {
 
     return route.fulfill({
       contentType: 'application/javascript',
-      body: `window._dubIdentity = {
-        identify: async () => {
-          window.identifyCalls = (window.identifyCalls || 0) + 1;
-          return '${VISITOR_ID}';
-        },
-      };`,
+      body: `window._dubIdentity = { identify: async () => '${VISITOR_ID}' };`,
     });
   });
 
   return agentRequests;
 }
 
-function mockPartnerClick(page: Page) {
-  return page.route('**/track/click', (route) =>
-    route.fulfill({
-      contentType: 'application/json',
-      body: JSON.stringify({
-        clickId: CLICK_ID,
-        partner: { id: 'pn_e2e', name: 'Partner', image: null },
-        discount: null,
-      }),
-    }),
-  );
-}
-
-function getIdentifyCalls(page: Page) {
-  return page.evaluate(() => (window as any).identifyCalls ?? 0);
-}
-
 async function getDubId(page: Page) {
   const cookies = await page.context().cookies(SITE);
 
@@ -96,7 +74,16 @@ test.describe('Identity tracking', () => {
     await serveSite(page);
     const agentRequests = await stubIdentityAgent(page);
 
-    await mockPartnerClick(page);
+    await page.route('**/track/click', (route) =>
+      route.fulfill({
+        contentType: 'application/json',
+        body: JSON.stringify({
+          clickId: CLICK_ID,
+          partner: { id: 'pn_e2e', name: 'Partner', image: null },
+          discount: null,
+        }),
+      }),
+    );
 
     await page.goto(`${SITE}/signup?via=partner`);
 
@@ -118,35 +105,4 @@ test.describe('Identity tracking', () => {
     expect(agentRequests).toHaveLength(0);
     expect(await getDubId(page)).toBe(CLICK_ID);
   });
-
-  test('preloads the agent for a partner click outside an identity path, without identifying it', async ({
-    page,
-  }) => {
-    await serveSite(page);
-    const agentRequests = await stubIdentityAgent(page);
-    await mockPartnerClick(page);
-
-    await page.goto(`${SITE}/pricing?via=partner`);
-
-    await expect.poll(() => agentRequests.length).toBe(1);
-    await expect.poll(() => getDubId(page)).toBe(CLICK_ID);
-    expect(await getIdentifyCalls(page)).toBe(0);
-  });
-
-  test('reuses the preloaded agent when trackIdentity() runs', async ({
-    page,
-  }) => {
-    await serveSite(page);
-    const agentRequests = await stubIdentityAgent(page);
-    await mockPartnerClick(page);
-
-    await page.goto(`${SITE}/pricing?via=partner`);
-    await expect.poll(() => agentRequests.length).toBe(1);
-
-    await page.evaluate(() => (window as any).dubAnalytics.trackIdentity());
-
-    expect(await getDubId(page)).toBe(`${CLICK_ID}_${VISITOR_ID}`);
-    expect(await getIdentifyCalls(page)).toBe(1);
-    expect(agentRequests).toHaveLength(1);
-  });
 });