@aman-sagar06077/zappa-analytics 0.1.3 → 0.1.4

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/README.md CHANGED
@@ -34,9 +34,27 @@ The SDK defaults to Zappa's hosted collector at `https://www.zappa.in/api/events
34
34
 
35
35
  Only initialize analytics when your consent policy permits it. Pass `enabled={false}` to the Next.js component until consent is granted, then render it with `enabled` set to `true`. `init` fails closed without a valid write key. The package tracks initial navigation, History API push/replace, query-only changes and browser back/forward, suppressing duplicate pageviews. It shares a persistent first-party visitor and session hint across tabs; the collector assigns the authoritative session after 30 minutes of inactivity or at a UTC day boundary. Use `analytics.reset()` to start a fresh anonymous identity and `analytics.optOut()` to stop collection and clear identifiers. Events are sent in batches of up to 20 and retried on transient network failures.
36
36
 
37
- ## Server-side AI crawler observations (Node.js 18+)
37
+ ## AI crawler observations on Next.js/Vercel
38
38
 
39
- Browser tracking cannot see crawlers that do not execute JavaScript. For Node/Express-style sites, install the optional server middleware from the separate `./crawler` export:
39
+ Browser analytics cannot see crawlers that do not execute JavaScript. For Next.js, add the collector to the site's existing `proxy.ts` (Next.js 16+) or `middleware.ts` (older Next.js). Do not replace existing auth, redirects, or rewrites; call the collector and keep the site's existing response logic:
40
+
41
+ ```ts
42
+ import { createNextCrawlerProxy } from '@aman-sagar06077/zappa-analytics/next-crawler';
43
+
44
+ const collectZappaCrawlerRequest = createNextCrawlerProxy({
45
+ projectId: process.env.ZAPPA_PROJECT_ID ?? '',
46
+ crawlerKey: process.env.ZAPPA_CRAWLER_KEY ?? '',
47
+ });
48
+
49
+ // Inside your existing proxy/middleware function, before returning its response:
50
+ collectZappaCrawlerRequest(request, event);
51
+ ```
52
+
53
+ The Next.js `event` argument keeps the small telemetry request alive after the site response is returned. The collector only reports recognized crawler-like GET/HEAD page requests, removes query strings, sends no IP address, and records status as `0` (unknown) because Proxy runs before the route. It recognizes search crawlers and user-triggered fetchers, including Perplexity-User and Claude-Agent. Extend your existing matcher to include public page routes while excluding static assets and API routes. In the Vercel project, set `ZAPPA_PROJECT_ID` and `ZAPPA_CRAWLER_KEY` as server-only environment variables, then redeploy. The key is private: never add a `NEXT_PUBLIC_` prefix or commit it.
54
+
55
+ ## AI crawler observations on Node/Express
56
+
57
+ For Node/Express-style sites, use the optional server middleware from the separate `./crawler` export:
40
58
 
41
59
  ```js
42
60
  import express from 'express';
@@ -51,4 +69,4 @@ app.use(createCrawlerMiddleware({
51
69
  }));
52
70
  ```
53
71
 
54
- Generate or rotate the private crawler key in the Zappa dashboard under **Overview → AI Traffic → AI crawlers**. Set `ZAPPA_PROJECT_ID` and `ZAPPA_CRAWLER_KEY` on the website's server only; never expose the crawler key to browser code. The middleware logs recognized crawler-like requests asynchronously after the response completes. It records the hostname, query-free path, method, status, timestamp, bounded User-Agent and a deduplication ID; it does not send request bodies or IP addresses. Requests are identified by User-Agent patterns only and are explicitly marked **unverified**—this does not prove that a request came from the crawler operator. Apply your site's usual consent/privacy policy and deploy middleware only on the Node server that receives the requests.
72
+ Generate or rotate the private crawler key in the Zappa dashboard under **Overview → AI Traffic → AI crawlers**. The middleware logs recognized crawler-like requests asynchronously after the response completes. It records the hostname, query-free path, method, status, timestamp, bounded User-Agent and a deduplication ID; it does not send request bodies or IP addresses. Requests are identified by User-Agent patterns only and are explicitly marked **unverified**—this does not prove that a request came from the crawler operator.
package/crawler.js CHANGED
@@ -1,5 +1,3 @@
1
- import { randomUUID } from 'node:crypto';
2
-
3
1
  const DEFAULT_ENDPOINT = 'https://www.zappa.in/api/ai-crawlers';
4
2
  const REGISTRY = [
5
3
  [/\bOAI-SearchBot\b/i, 'OAI-SearchBot', 'OpenAI', 'ai_search_crawler'],
@@ -7,7 +5,9 @@ const REGISTRY = [
7
5
  [/\bGPTBot\b/i, 'GPTBot', 'OpenAI', 'ai_training_crawler'],
8
6
  [/\bClaude-SearchBot\b/i, 'Claude-SearchBot', 'Anthropic', 'ai_search_crawler'],
9
7
  [/\bClaude-User\b/i, 'Claude-User', 'Anthropic', 'ai_assistant_fetcher'],
8
+ [/\bClaude-Agent\b/i, 'Claude-Agent', 'Anthropic', 'ai_assistant_fetcher'],
10
9
  [/\bClaudeBot\b/i, 'ClaudeBot', 'Anthropic', 'ai_training_crawler'],
10
+ [/\bPerplexity-User\b/i, 'Perplexity-User', 'Perplexity', 'ai_assistant_fetcher'],
11
11
  [/\bPerplexityBot\b/i, 'PerplexityBot', 'Perplexity', 'ai_search_crawler'],
12
12
  [/\bDuckAssistBot\b/i, 'DuckAssistBot', 'DuckDuckGo', 'ai_search_crawler'],
13
13
  [/\bGoogle-Extended\b/i, 'Google-Extended', 'Google', 'ai_training_crawler'],
@@ -71,7 +71,7 @@ export function createCrawlerMiddleware({ projectId, crawlerKey, endpoint = DEFA
71
71
  const payload = {
72
72
  projectId,
73
73
  requests: [{
74
- requestId: randomUUID(),
74
+ requestId: globalThis.crypto.randomUUID(),
75
75
  timestamp: new Date().toISOString(),
76
76
  hostname,
77
77
  path,
@@ -0,0 +1,22 @@
1
+ export type NextCrawlerRequest = {
2
+ url: string;
3
+ method?: string;
4
+ headers: { get(name: string): string | null };
5
+ };
6
+
7
+ export type NextCrawlerEvent = {
8
+ waitUntil(promise: Promise<unknown>): void;
9
+ };
10
+
11
+ export type NextCrawlerOptions = {
12
+ projectId: string;
13
+ crawlerKey: string;
14
+ endpoint?: string;
15
+ fetchImpl?: (input: URL, init: Record<string, unknown>) => Promise<unknown>;
16
+ timeoutMs?: number;
17
+ };
18
+
19
+ /** Create an Edge-safe collector for Next.js Proxy or Middleware request events. */
20
+ export function createNextCrawlerProxy(
21
+ options: NextCrawlerOptions,
22
+ ): (request: NextCrawlerRequest, event: NextCrawlerEvent) => boolean;
@@ -0,0 +1,82 @@
1
+ import { classifyCrawler } from './crawler.js';
2
+
3
+ const DEFAULT_ENDPOINT = 'https://www.zappa.in/api/ai-crawlers';
4
+ const PRIVATE_KEY = /^ZappaCrawler_[A-Za-z0-9_-]{32,}$/;
5
+ const HOST_LABELS = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
6
+ const NON_PAGE_PATH = /(?:^\/_next\/|^\/api\/|\.(?:avif|bmp|css|gif|ico|jpe?g|js|map|mjs|png|svg|webp|woff2?|ttf|eot|pdf|zip|xml)$)/i;
7
+
8
+ /**
9
+ * Create an Edge-safe collector for Next.js Proxy (or Middleware on older Next.js).
10
+ * Call it with the incoming Request and NextFetchEvent; it only schedules work for
11
+ * recognized crawler-like GET/HEAD requests and never changes the page response.
12
+ */
13
+ export function createNextCrawlerProxy({
14
+ projectId,
15
+ crawlerKey,
16
+ endpoint = DEFAULT_ENDPOINT,
17
+ fetchImpl = globalThis.fetch,
18
+ timeoutMs = 800,
19
+ } = {}) {
20
+ // Keep collection optional in local/preview environments where secrets are absent.
21
+ if (!projectId || !crawlerKey) return () => false;
22
+ if (typeof projectId !== 'string' || !projectId.trim()) throw new TypeError('projectId is required');
23
+ if (typeof crawlerKey !== 'string' || !PRIVATE_KEY.test(crawlerKey)) throw new TypeError('A private Zappa crawler key is required');
24
+ if (typeof fetchImpl !== 'function') throw new TypeError('Fetch is required');
25
+
26
+ const target = new URL(endpoint);
27
+ if (target.protocol !== 'https:' && target.hostname !== 'localhost') throw new TypeError('The crawler endpoint must use HTTPS');
28
+ const safeTimeout = Math.max(100, Math.min(Number(timeoutMs) || 800, 3000));
29
+
30
+ return function collectNextCrawlerRequest(request, event) {
31
+ const userAgent = request?.headers?.get?.('user-agent')?.slice(0, 1024) ?? '';
32
+ if (!classifyCrawler(userAgent)) return false;
33
+
34
+ const method = String(request.method || 'GET').toUpperCase();
35
+ if (method !== 'GET' && method !== 'HEAD') return false;
36
+
37
+ let url;
38
+ try {
39
+ url = new URL(request.url);
40
+ } catch {
41
+ return false;
42
+ }
43
+ const path = url.pathname;
44
+ if (!HOST_LABELS.test(url.hostname) || !path.startsWith('/') || path.length > 512 || NON_PAGE_PATH.test(path)) return false;
45
+ if (!event || typeof event.waitUntil !== 'function' || typeof globalThis.crypto?.randomUUID !== 'function') return false;
46
+
47
+ const controller = new AbortController();
48
+ const timeout = setTimeout(() => controller.abort(), safeTimeout);
49
+ const payload = {
50
+ projectId,
51
+ requests: [{
52
+ requestId: globalThis.crypto.randomUUID(),
53
+ timestamp: new Date().toISOString(),
54
+ hostname: url.hostname.toLowerCase().replace(/\.$/, ''),
55
+ path,
56
+ method,
57
+ // Proxy runs before the route, so the final HTTP status is not observable here.
58
+ // 0 is the API's documented sentinel for a status unavailable in Proxy.
59
+ statusCode: 0,
60
+ userAgent,
61
+ }],
62
+ };
63
+
64
+ const task = Promise.resolve()
65
+ .then(() => fetchImpl(target, {
66
+ method: 'POST',
67
+ headers: { 'Content-Type': 'application/json', 'X-Zappa-Crawler-Key': crawlerKey },
68
+ body: JSON.stringify(payload),
69
+ signal: controller.signal,
70
+ }))
71
+ .catch(() => {})
72
+ .finally(() => clearTimeout(timeout));
73
+
74
+ try {
75
+ event.waitUntil(task);
76
+ return true;
77
+ } catch {
78
+ // Telemetry must never break or delay the site's page response.
79
+ return false;
80
+ }
81
+ };
82
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aman-sagar06077/zappa-analytics",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Privacy-aware website analytics for Zappa projects.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -17,6 +17,10 @@
17
17
  "./crawler": {
18
18
  "types": "./crawler.d.ts",
19
19
  "default": "./crawler.js"
20
+ },
21
+ "./next-crawler": {
22
+ "types": "./next-crawler.d.ts",
23
+ "default": "./next-crawler.js"
20
24
  }
21
25
  },
22
26
  "files": [
@@ -26,6 +30,8 @@
26
30
  "next.d.ts",
27
31
  "crawler.js",
28
32
  "crawler.d.ts",
33
+ "next-crawler.js",
34
+ "next-crawler.d.ts",
29
35
  "README.md"
30
36
  ],
31
37
  "peerDependencies": {