Skip to content

Commit 753d142

Browse files
fix(analytics): use nullish checks in resolveDistinctId
CodeRabbit/Copilot feedback: truthy checks (`if (req.user?.id)`) would coerce `0` or empty-string identifiers to `'anonymous'`. Switch to `!= null` so any defined id/sessionID is preserved and stringified. Added 2 tests (`id: 0`, empty sessionID) — suite now 13 tests.
1 parent 60885fa commit 753d142

2 files changed

Lines changed: 28 additions & 2 deletions

File tree

lib/services/analytics.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,10 @@ const captureException = (err, ctx = {}) => {
136136
*/
137137
const resolveDistinctId = (req) => {
138138
if (!req) return 'anonymous';
139-
if (req.user?.id) return String(req.user.id);
140-
if (req.sessionID) return String(req.sessionID);
139+
// Use nullish checks so legitimate identifiers like `0` or empty strings
140+
// are preserved — any defined id is a valid PostHog distinctId.
141+
if (req.user?.id != null) return String(req.user.id);
142+
if (req.sessionID != null) return String(req.sessionID);
141143
return 'anonymous';
142144
};
143145

lib/services/tests/analytics.forRequest.unit.tests.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,30 @@ describe('analytics request-aware feature-flag helpers:', () => {
117117
);
118118
});
119119

120+
test('accepts user.id === 0 (nullish-check, not truthy)', async () => {
121+
const req = { user: { id: 0 }, sessionID: 'sess-abc' };
122+
123+
await AnalyticsService.getFeatureFlagForRequest('checkout-v2', req);
124+
125+
expect(mockPostHogInstance.getFeatureFlag).toHaveBeenCalledWith(
126+
'checkout-v2',
127+
'0',
128+
undefined,
129+
);
130+
});
131+
132+
test('accepts empty string sessionID when req.user is absent', async () => {
133+
const req = { sessionID: '' };
134+
135+
await AnalyticsService.getFeatureFlagForRequest('checkout-v2', req);
136+
137+
expect(mockPostHogInstance.getFeatureFlag).toHaveBeenCalledWith(
138+
'checkout-v2',
139+
'',
140+
undefined,
141+
);
142+
});
143+
120144
test('returns undefined when PostHog is not configured', async () => {
121145
await AnalyticsService.shutdown();
122146
jest.resetModules();

0 commit comments

Comments
 (0)