@nextanalytica/tag 1.0.1 → 1.1.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/README.md CHANGED
@@ -13,6 +13,8 @@ host, and the numbers are the same however the tag was installed. Page views on
13
13
 
14
14
  Your project key (`na_…`) is in nextanalytica, under Tracking.
15
15
 
16
+ The full guide is in the docs: [installation](https://nextanalytica.app/docs/tracking/installation), [the tag's API](https://nextanalytica.app/docs/reference/tag-api).
17
+
16
18
  ```sh
17
19
  npm install @nextanalytica/tag
18
20
  ```
@@ -100,17 +102,20 @@ nextanalytica.init("na_…");
100
102
  ## Your own events, consent and people
101
103
 
102
104
  ```ts
103
- import { track, order, consent, identify, group, setPersonProperties, reset } from "@nextanalytica/tag";
105
+ import { track, order, consent, identify, group, setPersonProperties, reset, heardFrom } from "@nextanalytica/tag";
104
106
 
105
107
  track("signup", { plan: "pro" });
106
108
  order({ ref: "A-1001", value: 49, currency: "EUR" });
109
+ heardFrom("ChatGPT told me"); // their answer to "How did you hear about us?"
107
110
  consent(true); // from your cookie banner; until a yes, no cookie and no id
108
111
  identify("user_42"); // your own user id after sign-in, never an email
109
112
  group("company", "acme", { plan: "pro" });
110
113
  reset(); // on sign-out
111
114
  ```
112
115
 
113
- Calls made before the tag has loaded wait and go in order. On the server they do nothing.
116
+ Calls made before the tag has loaded wait and go in order. On the server they do nothing. `heardFrom(answer)` is
117
+ `track("heard_from", { answer })`: your agent sees the people whose answer names an AI assistant, more in
118
+ https://nextanalytica.app/docs/tracking/custom-events.
114
119
 
115
120
  ## Events from your servers
116
121
 
@@ -127,6 +132,44 @@ Each event is `order` (with `value`, `currency`, `ref`) or `custom` (with `name`
127
132
  `user_id` is your own user id, the same one you pass to `identify`. Up to 50 events a request. They belong to no visit:
128
133
  your agent sees them as events, and as conversions under the channel "Server".
129
134
 
135
+ ## AI crawler hits from Cloudflare: `@nextanalytica/tag/cloudflare/crawlers`
136
+
137
+ A Cloudflare Worker that sends the requests of AI crawlers (GPTBot, ChatGPT-User, ClaudeBot and the rest) to
138
+ nextanalytica with your server key, after your site has answered. Your site's response is returned as it is, and a send
139
+ that fails never touches it. In your Worker's `src/worker.ts`:
140
+
141
+ ```ts
142
+ export { default } from "@nextanalytica/tag/cloudflare/crawlers";
143
+ ```
144
+
145
+ Store the key as the secret `NEXTANALYTICA_SERVER_KEY`, and set the route to fail open. The steps are at
146
+ https://nextanalytica.app/docs/tracking/ai-crawlers.
147
+
148
+ ## AI crawler hits from Next.js: `@nextanalytica/tag/next/crawlers`
149
+
150
+ Sends the requests of AI crawlers to nextanalytica with your server key, from your `middleware.ts`, after your site has
151
+ answered. The hit has no status: middleware runs before the route. A send that fails never touches your response.
152
+
153
+ ```ts
154
+ import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
155
+ import { sendCrawlerHit } from "@nextanalytica/tag/next/crawlers";
156
+
157
+ export function middleware(req: NextRequest, event: NextFetchEvent) {
158
+ sendCrawlerHit(req, event, { serverKey: process.env.NEXTANALYTICA_SERVER_KEY });
159
+ return NextResponse.next();
160
+ }
161
+ ```
162
+
163
+ Store the key as `NEXTANALYTICA_SERVER_KEY` and pass it from your own `middleware.ts`, as above: Next.js gives
164
+ middleware the environment variables it finds written in your code, and on Vercel's Edge runtime a read from inside a
165
+ package may not be one of them.
166
+
167
+ The address: on Vercel and Netlify the sender sends the address the platform sets. Anywhere else it sends none, and
168
+ hits are stored as `unknown`. It never sends `x-forwarded-for`, which a client can write. Behind a proxy that overwrites
169
+ a header with the client's address, pass `ip: (req) => req.headers.get("x-real-ip") ?? undefined` (or that header's
170
+ name). Use one sender per site: two senders count each hit twice. The steps are at
171
+ https://nextanalytica.app/docs/tracking/ai-crawlers.
172
+
130
173
  ## Returning visitors in Safari: `@nextanalytica/tag/server`
131
174
 
132
175
  After a visitor's yes, the tag keeps one id for them, `na_id`, in a cookie on your site's own domain, so `www.` and
@@ -173,7 +216,7 @@ app.use((req, res, next) => {
173
216
 
174
217
  `renew` acts on pages only, not on images, scripts or API calls. Pass `{ secure: false }` only for plain `http://`
175
218
  on your own machine. The cookie must come from the server that answers for your site's address: Safari still keeps a
176
- cookie for 7 days when it comes from a server at another company's address.
219
+ cookie for 7 days when it comes from a server at another company's address. More: [subdomains, domains and Safari](https://nextanalytica.app/docs/tracking/cross-domain).
177
220
 
178
221
  ## Content Security Policy
179
222
 
@@ -200,4 +243,5 @@ Every component and `init` take the same options:
200
243
  | `vitals: "all"` | Measure Web Vitals on every page view instead of a sample |
201
244
  | `search: ["q"]` | The URL parameters that hold your site search's query |
202
245
  | `domains: ["pay.example"]` | Your other domains in this project: after consent, a link to one of them carries the visitor (two minutes) |
246
+ | `release: "a1b2c3"` | The release of your app (a commit or a version, up to 80 characters), so your agent can compare releases |
203
247
  | `api_host` | Where `t.js` is served from, if not `https://t.nextanalytica.app` |
@@ -0,0 +1,16 @@
1
+ export interface CrawlerEnv {
2
+ NEXTANALYTICA_SERVER_KEY: string;
3
+ }
4
+ export interface CrawlerCtx {
5
+ waitUntil(p: Promise<unknown>): void;
6
+ passThroughOnException(): void;
7
+ }
8
+ export declare function crawlerWorker(o?: {
9
+ apiHost?: string;
10
+ }): {
11
+ fetch(req: Request, env: CrawlerEnv, ctx: CrawlerCtx): Promise<Response>;
12
+ };
13
+ declare const _default: {
14
+ fetch(req: Request, env: CrawlerEnv, ctx: CrawlerCtx): Promise<Response>;
15
+ };
16
+ export default _default;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The Cloudflare Worker that sends AI crawler hits to nextanalytica (the read-visit-money chain, sender "cloudflare").
3
+ * It passes every request to the origin, returns the origin's response as it is, and, for a request whose user agent is
4
+ * an AI bot's (`AI_CRAWLER_UA`), sends one hit to `POST /b` after the response, with `ctx.waitUntil`: the visitor never
5
+ * waits for it, and a send that fails or takes over 1 second is dropped. Any other request is never sent.
6
+ *
7
+ * Deploy it with `src/worker.ts` in a Wrangler project, a route on `example.com/*` and the secret
8
+ * `wrangler secret put NEXTANALYTICA_SERVER_KEY`:
9
+ *
10
+ * export { default } from "@nextanalytica/tag/cloudflare/crawlers";
11
+ *
12
+ * The route must be set to fail open: on the Workers Free plan's 100,000 requests a day, a route that fails closed shows
13
+ * error 1027 (https://developers.cloudflare.com/workers/platform/limits). Docs: https://nextanalytica.app/docs/tracking/ai-crawlers
14
+ */
15
+ import { API_HOST } from "./index.js";
16
+ import { AI_CRAWLER_UA } from "./crawlers.js";
17
+ import { postCrawlerHit } from "./crawler-send.js";
18
+ export function crawlerWorker(o = {}) {
19
+ const url = `${o.apiHost ?? API_HOST}/b`;
20
+ return {
21
+ async fetch(req, env, ctx) {
22
+ // first, so an exception anywhere below sends the request on to the origin as if the Worker weren't there
23
+ ctx.passThroughOnException();
24
+ const res = await fetch(req);
25
+ const ua = req.headers.get("user-agent") ?? "";
26
+ if (!env.NEXTANALYTICA_SERVER_KEY || !AI_CRAWLER_UA.test(ua))
27
+ return res;
28
+ const { hostname: host, pathname: path } = new URL(req.url), ip = req.headers.get("cf-connecting-ip");
29
+ const hit = { ts: Date.now(), host, path, status: res.status, ua, ...(ip ? { ip } : {}) };
30
+ ctx.waitUntil(postCrawlerHit(url, env.NEXTANALYTICA_SERVER_KEY, "cloudflare", hit));
31
+ return res;
32
+ },
33
+ };
34
+ }
35
+ export default crawlerWorker();
@@ -0,0 +1,9 @@
1
+ export interface CrawlerHit {
2
+ ts: number;
3
+ host: string;
4
+ path: string;
5
+ status?: number;
6
+ ua: string;
7
+ ip?: string;
8
+ }
9
+ export declare function postCrawlerHit(url: string, key: string, sender: "cloudflare" | "next", hit: CrawlerHit): Promise<void>;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The one send the crawler senders share (Cloudflare Worker, Next.js middleware): one hit to `POST /b` with the server
3
+ * key as a bearer, 1 second to answer, every failure swallowed. It returns the promise for the caller's `waitUntil`, so
4
+ * the visitor never waits for it.
5
+ */
6
+ /** The senders' own version, sent with every batch. */
7
+ const VERSION = "1.0.0";
8
+ export function postCrawlerHit(url, key, sender, hit) {
9
+ return fetch(url, {
10
+ method: "POST", signal: AbortSignal.timeout(1000),
11
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
12
+ body: JSON.stringify({ sender, version: VERSION, hits: [hit] }),
13
+ }).then(() => { }, () => { });
14
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The user agents of AI crawlers and assistants, as one regex every sender ships (the Cloudflare Worker, the WordPress
3
+ * plugin, the Next.js middleware): a request whose user agent matches is sent to the edge, any other never is. The edge's
4
+ * `AI_BOTS` (apps/edge/src/bots.ts) names the same bots with their owner and purpose, and its test checks the two agree.
5
+ *
6
+ * Only syntax that JavaScript and PHP's PCRE share: plain alternation of names and the case-insensitive flag, so
7
+ * `.source` can be copied into PHP as it is.
8
+ */
9
+ export declare const AI_CRAWLER_UA: RegExp;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The user agents of AI crawlers and assistants, as one regex every sender ships (the Cloudflare Worker, the WordPress
3
+ * plugin, the Next.js middleware): a request whose user agent matches is sent to the edge, any other never is. The edge's
4
+ * `AI_BOTS` (apps/edge/src/bots.ts) names the same bots with their owner and purpose, and its test checks the two agree.
5
+ *
6
+ * Only syntax that JavaScript and PHP's PCRE share: plain alternation of names and the case-insensitive flag, so
7
+ * `.source` can be copied into PHP as it is.
8
+ */
9
+ export const AI_CRAWLER_UA = /GPTBot|OAI-SearchBot|ChatGPT-User|ClaudeBot|Claude-SearchBot|Claude-User|PerplexityBot|Perplexity-User|Meta-ExternalAgent|Meta-ExternalFetcher|Amazonbot|MistralAI-User|Bytespider|CCBot|DuckAssistBot/i;
package/dist/index.d.ts CHANGED
@@ -40,6 +40,8 @@ export interface Options {
40
40
  search?: string[];
41
41
  /** Your other domains in this project, for example ["shop.io"]: a link to one of them carries the visitor, after consent. */
42
42
  domains?: string[];
43
+ /** The release of your app (a commit, a version: up to 80 letters, digits and . _ : + / @ -), so your agent can compare releases. */
44
+ release?: string;
43
45
  }
44
46
  declare global {
45
47
  interface Window {
@@ -85,6 +87,13 @@ export declare const group: (type: string, key: string, props?: Props) => void;
85
87
  export declare const setPersonProperties: (props: Props) => void;
86
88
  /** On sign-out: forget the person on this device. */
87
89
  export declare const reset: () => void;
90
+ /**
91
+ * What the person says about where they heard of you ("ChatGPT told me"), from your form or checkout: a `heard_from`
92
+ * event with the answer, cut at 200 characters (t.js then keeps the first 100, as of any property). nextanalytica reads
93
+ * the AI assistant it names; your agent counts those people as `self_reported`. On a plain page:
94
+ * `nextanalytica.track("heard_from", { answer })`.
95
+ */
96
+ export declare const heardFrom: (answer: string) => void;
88
97
  declare const nextanalytica: {
89
98
  init: typeof init;
90
99
  track: typeof track;
@@ -94,5 +103,6 @@ declare const nextanalytica: {
94
103
  group: typeof group;
95
104
  setPersonProperties: typeof setPersonProperties;
96
105
  reset: typeof reset;
106
+ heardFrom: typeof heardFrom;
97
107
  };
98
108
  export default nextanalytica;
package/dist/index.js CHANGED
@@ -36,6 +36,8 @@ export function attributes(project, o = {}) {
36
36
  a["data-vitals"] = "all";
37
37
  if (o.domains?.length)
38
38
  a["data-domains"] = o.domains.join(",");
39
+ if (o.release)
40
+ a["data-release"] = o.release;
39
41
  if (o.search?.length)
40
42
  a["data-search"] = o.search.join(",");
41
43
  return a;
@@ -111,5 +113,12 @@ export const group = (type, key, props) => call("group", type, key, props);
111
113
  export const setPersonProperties = (props) => call("setPersonProperties", props);
112
114
  /** On sign-out: forget the person on this device. */
113
115
  export const reset = () => call("reset");
114
- const nextanalytica = { init, track, order, consent, identify, group, setPersonProperties, reset };
116
+ /**
117
+ * What the person says about where they heard of you ("ChatGPT told me"), from your form or checkout: a `heard_from`
118
+ * event with the answer, cut at 200 characters (t.js then keeps the first 100, as of any property). nextanalytica reads
119
+ * the AI assistant it names; your agent counts those people as `self_reported`. On a plain page:
120
+ * `nextanalytica.track("heard_from", { answer })`.
121
+ */
122
+ export const heardFrom = (answer) => track("heard_from", { answer: answer.slice(0, 200) });
123
+ const nextanalytica = { init, track, order, consent, identify, group, setPersonProperties, reset, heardFrom };
115
124
  export default nextanalytica;
@@ -0,0 +1,8 @@
1
+ export declare function sendCrawlerHit(req: Request, event: {
2
+ waitUntil(p: Promise<unknown>): void;
3
+ }, o?: {
4
+ serverKey?: string;
5
+ apiHost?: string;
6
+ /** The client's address, for a proxy that overwrites a header with it; by default only Vercel's and Netlify's own. */
7
+ ip?: (req: Request) => string | undefined;
8
+ }): void;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Sends AI crawler hits to nextanalytica from Next.js middleware (the read-visit-money chain, sender "next"). Call it in
3
+ * `middleware.ts` and return your response as usual: for a request whose user agent is an AI bot's (`AI_CRAWLER_UA`) it
4
+ * sends one hit to `POST /b` through `event.waitUntil`, so the visitor never waits, and a send that fails or takes over
5
+ * 1 second is dropped. Any other request is never sent. Middleware runs before the route, so the hit has no status.
6
+ *
7
+ * export function middleware(req: NextRequest, event: NextFetchEvent) {
8
+ * sendCrawlerHit(req, event, { serverKey: process.env.NEXTANALYTICA_SERVER_KEY });
9
+ * return NextResponse.next();
10
+ * }
11
+ *
12
+ * Pass the key from your own `middleware.ts`, as above: Next.js gives middleware the environment variables it finds
13
+ * written as `process.env.NAME` in the code it bundles, and on Vercel's Edge runtime a read from inside a package may
14
+ * not be one it finds. Without `serverKey`, the sender reads `NEXTANALYTICA_SERVER_KEY` itself where it can.
15
+ *
16
+ * The address: `x-forwarded-for` is never sent by default, since a client can write its first entry wherever a proxy
17
+ * appends to it, and a borrowed bot name with a borrowed address would read as verified. On Vercel (`VERCEL` set) the
18
+ * sender sends the address Vercel sets (`x-vercel-forwarded-for`, else `x-real-ip`); on Netlify (`NETLIFY` set),
19
+ * `x-nf-client-connection-ip`. Anywhere else no address is sent, and the edge stores the hit as `unknown`, never
20
+ * `verified`. Behind a proxy that overwrites a header with the client's address, pass `ip` to read it.
21
+ *
22
+ * Its own entry (`@nextanalytica/tag/next/crawlers`), not part of `./next`, which client components import.
23
+ * Docs: https://nextanalytica.app/docs/tracking/ai-crawlers
24
+ */
25
+ import { API_HOST } from "./index.js";
26
+ import { AI_CRAWLER_UA } from "./crawlers.js";
27
+ import { postCrawlerHit } from "./crawler-send.js";
28
+ /** Whether the runtime has an env; each name is then read as `process.env.NAME`, the way Next.js finds it. */
29
+ const hasEnv = () => typeof process !== "undefined" && !!process && !!process.env;
30
+ /** The client's address as the platform the app runs on sets it, or undefined: never a header a client can write. */
31
+ function platformIp(req) {
32
+ const h = (name) => req.headers.get(name)?.split(",")[0]?.trim() || undefined;
33
+ if (hasEnv() && process.env.VERCEL)
34
+ return h("x-vercel-forwarded-for") ?? h("x-real-ip");
35
+ if (hasEnv() && process.env.NETLIFY)
36
+ return h("x-nf-client-connection-ip");
37
+ return undefined;
38
+ }
39
+ export function sendCrawlerHit(req, event, o = {}) {
40
+ const key = o.serverKey ?? (hasEnv() ? process.env.NEXTANALYTICA_SERVER_KEY : undefined);
41
+ const ua = req.headers.get("user-agent") ?? "";
42
+ if (!key || !AI_CRAWLER_UA.test(ua))
43
+ return;
44
+ const { hostname: host, pathname: path } = new URL(req.url), ip = (o.ip ?? platformIp)(req);
45
+ event.waitUntil(postCrawlerHit(`${o.apiHost ?? API_HOST}/b`, key, "next", { ts: Date.now(), host, path, ua, ...(ip ? { ip } : {}) }));
46
+ }
package/dist/nuxt.d.ts CHANGED
@@ -30,6 +30,7 @@ declare namespace nextanalyticaModule {
30
30
  vitals?: "all";
31
31
  search?: string[];
32
32
  domains?: string[];
33
+ release?: string;
33
34
  project?: string;
34
35
  }>;
35
36
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nextanalytica/tag",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "The nextanalytica tag for JavaScript apps: one component per framework, the same t.js underneath.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -38,6 +38,10 @@
38
38
  "types": "./dist/next.d.ts",
39
39
  "import": "./dist/next.js"
40
40
  },
41
+ "./next/crawlers": {
42
+ "types": "./dist/next-crawlers.d.ts",
43
+ "import": "./dist/next-crawlers.js"
44
+ },
41
45
  "./vue": {
42
46
  "types": "./dist/vue.d.ts",
43
47
  "import": "./dist/vue.js"
@@ -54,6 +58,10 @@
54
58
  "types": "./dist/server.d.ts",
55
59
  "import": "./dist/server.js"
56
60
  },
61
+ "./cloudflare/crawlers": {
62
+ "types": "./dist/cloudflare.d.ts",
63
+ "import": "./dist/cloudflare.js"
64
+ },
57
65
  "./astro": "./src/astro/Analytics.astro",
58
66
  "./gatsby/package.json": "./gatsby/package.json",
59
67
  "./gatsby/*": "./gatsby/*",