@codaco/analytics 8.0.0 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/MIGRATION.md +404 -0
- package/README.md +486 -4
- package/dist/chunk-3NEQVIC4.js +72 -0
- package/dist/chunk-3NEQVIC4.js.map +1 -0
- package/dist/index.d.ts +113 -82
- package/dist/index.js +188 -160
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +44 -0
- package/dist/server.js +153 -0
- package/dist/server.js.map +1 -0
- package/dist/types-Ymgjicqi.d.ts +145 -0
- package/package.json +27 -7
- package/src/__tests__/client.test.ts +276 -0
- package/src/__tests__/index.test.ts +207 -0
- package/src/__tests__/utils.test.ts +105 -0
- package/src/client.ts +151 -0
- package/src/config.ts +92 -0
- package/src/hooks.ts +79 -0
- package/src/index.ts +69 -237
- package/src/provider.tsx +60 -0
- package/src/server.ts +213 -0
- package/src/types.ts +183 -0
- package/src/utils.ts +1 -0
- package/tsconfig.json +1 -1
- package/vitest.config.ts +18 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @codaco/analytics
|
|
2
2
|
|
|
3
|
+
## 10.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- b3d4d4b: Initial alpha release of the new analytics package with PostHog integration
|
|
8
|
+
|
|
9
|
+
## 9.0.0
|
|
10
|
+
|
|
11
|
+
### Major Changes
|
|
12
|
+
|
|
13
|
+
- Initial release of the new analytics package with PostHog integration
|
|
14
|
+
|
|
3
15
|
## 8.0.0
|
|
4
16
|
|
|
5
17
|
### Major Changes
|
package/MIGRATION.md
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
# Migration Guide: Old Analytics → PostHog
|
|
2
|
+
|
|
3
|
+
This guide will help you migrate from the old custom analytics system to the new PostHog-based implementation.
|
|
4
|
+
|
|
5
|
+
## Overview of Changes
|
|
6
|
+
|
|
7
|
+
### What's Changing
|
|
8
|
+
|
|
9
|
+
| Old System | New System |
|
|
10
|
+
|------------|------------|
|
|
11
|
+
| Custom analytics backend | PostHog Cloud (US) |
|
|
12
|
+
| Direct API routes (`/api/analytics`) | Cloudflare Worker reverse proxy |
|
|
13
|
+
| `createRouteHandler()` | `AnalyticsProvider` |
|
|
14
|
+
| `makeEventTracker()` | `useAnalytics()` hook |
|
|
15
|
+
| `AppSetup`, `ProtocolInstalled`, etc. | `app_setup`, `protocol_installed`, etc. |
|
|
16
|
+
| Manual IP geolocation | PostHog automatic geolocation |
|
|
17
|
+
| Custom dashboard (analytics-web) | PostHog dashboard |
|
|
18
|
+
|
|
19
|
+
### What's New
|
|
20
|
+
|
|
21
|
+
- **Feature Flags & A/B Testing**: Built-in support for experiments
|
|
22
|
+
- **Session Replay**: Optional recording of user sessions (disabled by default)
|
|
23
|
+
- **Better Error Tracking**: Enhanced error reporting with stack traces
|
|
24
|
+
- **Real-time Dashboard**: PostHog's powerful analytics interface
|
|
25
|
+
- **Server-side Analytics**: Dedicated API for backend tracking
|
|
26
|
+
|
|
27
|
+
## Step-by-Step Migration
|
|
28
|
+
|
|
29
|
+
### 1. Set Up Cloudflare Worker (One-Time Setup)
|
|
30
|
+
|
|
31
|
+
Deploy the reverse proxy to `ph-relay.networkcanvas.com`:
|
|
32
|
+
|
|
33
|
+
1. Follow instructions in `/cloudflare-worker/README.md`
|
|
34
|
+
2. Deploy the worker code from `/cloudflare-worker/posthog-proxy.js`
|
|
35
|
+
3. Configure custom domain: `ph-relay.networkcanvas.com`
|
|
36
|
+
4. Verify it's working with a test request
|
|
37
|
+
|
|
38
|
+
### 2. Update Environment Variables
|
|
39
|
+
|
|
40
|
+
**Old `.env.local`:**
|
|
41
|
+
```bash
|
|
42
|
+
# Not needed anymore - analytics was configured in code
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
**New `.env.local`:**
|
|
46
|
+
```bash
|
|
47
|
+
# Required
|
|
48
|
+
NEXT_PUBLIC_POSTHOG_KEY=phc_your_posthog_project_key
|
|
49
|
+
NEXT_PUBLIC_INSTALLATION_ID=your-unique-installation-id
|
|
50
|
+
|
|
51
|
+
# Optional (has sensible defaults)
|
|
52
|
+
NEXT_PUBLIC_POSTHOG_HOST=https://ph-relay.networkcanvas.com
|
|
53
|
+
NEXT_PUBLIC_DISABLE_ANALYTICS=false
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### 3. Update Dependencies
|
|
57
|
+
|
|
58
|
+
The package now requires React as a peer dependency:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pnpm install @codaco/analytics@latest
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 4. Migrate Client-Side Code
|
|
65
|
+
|
|
66
|
+
#### Before: Route Handler + Event Tracker
|
|
67
|
+
|
|
68
|
+
```tsx
|
|
69
|
+
// app/api/analytics/route.ts
|
|
70
|
+
import { createRouteHandler } from '@codaco/analytics';
|
|
71
|
+
|
|
72
|
+
export const POST = createRouteHandler({
|
|
73
|
+
installationId: process.env.INSTALLATION_ID!,
|
|
74
|
+
platformUrl: 'https://analytics.networkcanvas.com',
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
```tsx
|
|
79
|
+
// components/MyComponent.tsx
|
|
80
|
+
import { makeEventTracker } from '@codaco/analytics';
|
|
81
|
+
|
|
82
|
+
const trackEvent = makeEventTracker();
|
|
83
|
+
|
|
84
|
+
function MyComponent() {
|
|
85
|
+
const handleAction = async () => {
|
|
86
|
+
await trackEvent({
|
|
87
|
+
type: 'AppSetup',
|
|
88
|
+
metadata: { version: '1.0.0' }
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
#### After: Provider + Hook
|
|
95
|
+
|
|
96
|
+
```tsx
|
|
97
|
+
// app/layout.tsx
|
|
98
|
+
import { AnalyticsProvider } from '@codaco/analytics';
|
|
99
|
+
|
|
100
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
101
|
+
return (
|
|
102
|
+
<AnalyticsProvider
|
|
103
|
+
config={{
|
|
104
|
+
installationId: process.env.NEXT_PUBLIC_INSTALLATION_ID!,
|
|
105
|
+
}}
|
|
106
|
+
>
|
|
107
|
+
{children}
|
|
108
|
+
</AnalyticsProvider>
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```tsx
|
|
114
|
+
// components/MyComponent.tsx
|
|
115
|
+
import { useAnalytics } from '@codaco/analytics';
|
|
116
|
+
|
|
117
|
+
function MyComponent() {
|
|
118
|
+
const { trackEvent } = useAnalytics();
|
|
119
|
+
|
|
120
|
+
const handleAction = () => {
|
|
121
|
+
// No need to await - it's fire-and-forget
|
|
122
|
+
trackEvent('app_setup', {
|
|
123
|
+
metadata: { version: '1.0.0' }
|
|
124
|
+
});
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**Key Changes:**
|
|
130
|
+
- Remove `/api/analytics/route.ts` - no longer needed
|
|
131
|
+
- Wrap app in `AnalyticsProvider`
|
|
132
|
+
- Use `useAnalytics()` hook instead of `makeEventTracker()`
|
|
133
|
+
- Event names are now `snake_case`
|
|
134
|
+
- No need to `await` tracking calls
|
|
135
|
+
|
|
136
|
+
### 5. Update Event Names
|
|
137
|
+
|
|
138
|
+
All event names must be converted from PascalCase to snake_case:
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
// Old → New
|
|
142
|
+
'AppSetup' → 'app_setup'
|
|
143
|
+
'ProtocolInstalled' → 'protocol_installed'
|
|
144
|
+
'InterviewStarted' → 'interview_started'
|
|
145
|
+
'InterviewCompleted' → 'interview_completed'
|
|
146
|
+
'DataExported' → 'data_exported'
|
|
147
|
+
'Error' → 'error' (but use trackError() instead)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
**Migration Helper:**
|
|
151
|
+
|
|
152
|
+
The package exports a `legacyEventTypeMap` for reference:
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
import { legacyEventTypeMap } from '@codaco/analytics';
|
|
156
|
+
|
|
157
|
+
// Maps old names to new names
|
|
158
|
+
console.log(legacyEventTypeMap.AppSetup); // 'app_setup'
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### 6. Migrate Error Tracking
|
|
162
|
+
|
|
163
|
+
#### Before:
|
|
164
|
+
|
|
165
|
+
```tsx
|
|
166
|
+
try {
|
|
167
|
+
// code
|
|
168
|
+
} catch (error) {
|
|
169
|
+
await trackEvent({
|
|
170
|
+
type: 'Error',
|
|
171
|
+
message: error.message,
|
|
172
|
+
name: error.name,
|
|
173
|
+
stack: error.stack,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
#### After:
|
|
179
|
+
|
|
180
|
+
```tsx
|
|
181
|
+
try {
|
|
182
|
+
// code
|
|
183
|
+
} catch (error) {
|
|
184
|
+
trackError(error as Error, {
|
|
185
|
+
metadata: { context: 'import' }
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
**Benefits:**
|
|
191
|
+
- Dedicated `trackError()` method
|
|
192
|
+
- Automatic error serialization
|
|
193
|
+
- Better stack trace formatting in PostHog
|
|
194
|
+
- Additional context via metadata
|
|
195
|
+
|
|
196
|
+
### 7. Migrate Server-Side Code
|
|
197
|
+
|
|
198
|
+
For server actions, API routes, or backend code:
|
|
199
|
+
|
|
200
|
+
#### Before:
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
// Not well supported in old system
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
#### After:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
import { serverAnalytics } from '@codaco/analytics/server';
|
|
210
|
+
|
|
211
|
+
export async function POST(request: Request) {
|
|
212
|
+
serverAnalytics.trackEvent('data_exported', {
|
|
213
|
+
metadata: { format: 'csv' }
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### 8. Remove Old Analytics Infrastructure (Optional)
|
|
219
|
+
|
|
220
|
+
During the transition period, you can keep the old `analytics-web` app running. Once fully migrated:
|
|
221
|
+
|
|
222
|
+
1. Stop the `analytics-web` app
|
|
223
|
+
2. Remove or archive the app directory
|
|
224
|
+
3. Remove the PostgreSQL database (after backing up if needed)
|
|
225
|
+
4. Update any internal documentation
|
|
226
|
+
|
|
227
|
+
## Feature Comparison
|
|
228
|
+
|
|
229
|
+
### What You Gain
|
|
230
|
+
|
|
231
|
+
✅ **Feature Flags & A/B Testing**
|
|
232
|
+
```tsx
|
|
233
|
+
const { isFeatureEnabled, getFeatureFlag } = useAnalytics();
|
|
234
|
+
|
|
235
|
+
if (isFeatureEnabled('new-ui')) {
|
|
236
|
+
return <NewUI />;
|
|
237
|
+
}
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
✅ **Better Dashboard**
|
|
241
|
+
- Real-time event streaming
|
|
242
|
+
- Funnel analysis
|
|
243
|
+
- Retention cohorts
|
|
244
|
+
- User paths
|
|
245
|
+
- Custom insights
|
|
246
|
+
|
|
247
|
+
✅ **Session Replay** (Optional)
|
|
248
|
+
```tsx
|
|
249
|
+
<AnalyticsProvider
|
|
250
|
+
config={{
|
|
251
|
+
installationId: 'xyz',
|
|
252
|
+
posthogOptions: {
|
|
253
|
+
disable_session_recording: false, // Enable if needed
|
|
254
|
+
}
|
|
255
|
+
}}
|
|
256
|
+
>
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
✅ **Server-Side Tracking**
|
|
260
|
+
```ts
|
|
261
|
+
import { serverAnalytics } from '@codaco/analytics/server';
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
### What You Lose
|
|
265
|
+
|
|
266
|
+
❌ **Custom Dashboard** - Use PostHog dashboard instead
|
|
267
|
+
❌ **Self-Hosted Backend** - Now using PostHog Cloud
|
|
268
|
+
❌ **Manual Geolocation Control** - PostHog handles this automatically
|
|
269
|
+
|
|
270
|
+
## Testing Your Migration
|
|
271
|
+
|
|
272
|
+
### 1. Parallel Tracking (Recommended)
|
|
273
|
+
|
|
274
|
+
During migration, track events to both systems:
|
|
275
|
+
|
|
276
|
+
```tsx
|
|
277
|
+
const { trackEvent: trackNewEvent } = useAnalytics();
|
|
278
|
+
const trackOldEvent = makeEventTracker();
|
|
279
|
+
|
|
280
|
+
const handleAction = async () => {
|
|
281
|
+
// Track to both
|
|
282
|
+
trackNewEvent('app_setup', { metadata: { version: '1.0.0' } });
|
|
283
|
+
await trackOldEvent({ type: 'AppSetup', metadata: { version: '1.0.0' } });
|
|
284
|
+
};
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### 2. Verify Events in PostHog
|
|
288
|
+
|
|
289
|
+
1. Log in to PostHog dashboard
|
|
290
|
+
2. Go to "Events" or "Activity"
|
|
291
|
+
3. Verify events are appearing with correct:
|
|
292
|
+
- Event names (`app_setup`, etc.)
|
|
293
|
+
- Properties (including `installation_id`)
|
|
294
|
+
- Timestamps
|
|
295
|
+
|
|
296
|
+
### 3. Test Feature Flags
|
|
297
|
+
|
|
298
|
+
1. Create a test flag in PostHog
|
|
299
|
+
2. Use the hooks in your app:
|
|
300
|
+
```tsx
|
|
301
|
+
const isEnabled = useFeatureFlag('test-flag');
|
|
302
|
+
console.log('Flag enabled:', isEnabled);
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### 4. Test Analytics Disabling
|
|
306
|
+
|
|
307
|
+
```bash
|
|
308
|
+
NEXT_PUBLIC_DISABLE_ANALYTICS=true pnpm dev
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Verify no events are sent to PostHog.
|
|
312
|
+
|
|
313
|
+
## Common Migration Issues
|
|
314
|
+
|
|
315
|
+
### Issue: Events Not Appearing
|
|
316
|
+
|
|
317
|
+
**Solution:**
|
|
318
|
+
1. Check `NEXT_PUBLIC_POSTHOG_KEY` is set correctly
|
|
319
|
+
2. Verify Cloudflare Worker is deployed
|
|
320
|
+
3. Enable debug mode: `debug: true` in config
|
|
321
|
+
4. Check browser console for errors
|
|
322
|
+
|
|
323
|
+
### Issue: TypeScript Errors
|
|
324
|
+
|
|
325
|
+
**Solution:**
|
|
326
|
+
```bash
|
|
327
|
+
pnpm install @types/react --save-dev
|
|
328
|
+
pnpm run typecheck
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
### Issue: "useAnalytics must be used within AnalyticsProvider"
|
|
332
|
+
|
|
333
|
+
**Solution:**
|
|
334
|
+
Ensure `AnalyticsProvider` wraps your app in the root layout:
|
|
335
|
+
|
|
336
|
+
```tsx
|
|
337
|
+
// app/layout.tsx
|
|
338
|
+
<AnalyticsProvider config={{ ... }}>
|
|
339
|
+
{children}
|
|
340
|
+
</AnalyticsProvider>
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
### Issue: Server-Side Analytics Not Working
|
|
344
|
+
|
|
345
|
+
**Solution:**
|
|
346
|
+
Ensure environment variables are set:
|
|
347
|
+
```bash
|
|
348
|
+
INSTALLATION_ID=your-id # or NEXT_PUBLIC_INSTALLATION_ID
|
|
349
|
+
POSTHOG_KEY=your-key # or NEXT_PUBLIC_POSTHOG_KEY
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
## Rollback Plan
|
|
353
|
+
|
|
354
|
+
If you need to rollback:
|
|
355
|
+
|
|
356
|
+
1. **Keep the old code** in a separate branch during migration
|
|
357
|
+
2. **Maintain parallel tracking** for a transition period
|
|
358
|
+
3. **Keep analytics-web running** until confident in migration
|
|
359
|
+
4. **Document any custom queries** you rely on in the old system
|
|
360
|
+
|
|
361
|
+
To rollback:
|
|
362
|
+
|
|
363
|
+
```bash
|
|
364
|
+
git revert <migration-commit>
|
|
365
|
+
pnpm install
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
Then redeploy your app.
|
|
369
|
+
|
|
370
|
+
## Migration Checklist
|
|
371
|
+
|
|
372
|
+
Use this checklist to track your migration progress:
|
|
373
|
+
|
|
374
|
+
- [ ] Deploy Cloudflare Worker reverse proxy
|
|
375
|
+
- [ ] Set up PostHog project and get API key
|
|
376
|
+
- [ ] Update `.env` files with new variables
|
|
377
|
+
- [ ] Install updated `@codaco/analytics` package
|
|
378
|
+
- [ ] Add `AnalyticsProvider` to root layout
|
|
379
|
+
- [ ] Update all event tracking calls to use `useAnalytics()`
|
|
380
|
+
- [ ] Convert all event names to `snake_case`
|
|
381
|
+
- [ ] Update error tracking to use `trackError()`
|
|
382
|
+
- [ ] Add server-side tracking where needed
|
|
383
|
+
- [ ] Test events appearing in PostHog dashboard
|
|
384
|
+
- [ ] Test analytics disabling
|
|
385
|
+
- [ ] Remove old `/api/analytics` route
|
|
386
|
+
- [ ] Update internal documentation
|
|
387
|
+
- [ ] (Optional) Archive/remove `analytics-web` app
|
|
388
|
+
|
|
389
|
+
## Need Help?
|
|
390
|
+
|
|
391
|
+
- Check the [main README](./README.md) for full API documentation
|
|
392
|
+
- Review the [PostHog documentation](https://posthog.com/docs)
|
|
393
|
+
- Open an issue on GitHub
|
|
394
|
+
- Contact: hello@complexdatacollective.org
|
|
395
|
+
|
|
396
|
+
## Next Steps
|
|
397
|
+
|
|
398
|
+
After migrating:
|
|
399
|
+
|
|
400
|
+
1. **Explore PostHog Dashboard**: Set up custom insights, funnels, and retention reports
|
|
401
|
+
2. **Create Feature Flags**: Start using feature flags for gradual rollouts
|
|
402
|
+
3. **Set Up Alerts**: Configure PostHog to alert you of anomalies
|
|
403
|
+
4. **Review Privacy Settings**: Ensure PostHog configuration matches your privacy requirements
|
|
404
|
+
5. **Archive Old Data**: Export data from the old system if needed for historical analysis
|