@adwait12345/telemetry-next 0.1.2 → 0.1.3
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 +153 -0
- package/package.json +5 -1
- package/src/index.ts +0 -89
- package/tsconfig.json +0 -9
package/README.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# `@adwait12345/telemetry-next`
|
|
2
|
+
|
|
3
|
+
Next.js middleware adapter for the Telemetry SDK. Detects bots and crawlers on every server-side request and sends tracking payloads to the Telemetry API — without slowing down your users.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- Next.js **13.0.0 or later** (App Router or Pages Router)
|
|
10
|
+
- A Telemetry account with a **Project ID** and **Server Secret**
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @adwait12345/telemetry-next @adwait12345/telemetry-core
|
|
18
|
+
# or
|
|
19
|
+
pnpm add @adwait12345/telemetry-next @adwait12345/telemetry-core
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Setup
|
|
25
|
+
|
|
26
|
+
### 1. Create `middleware.ts` at the root of your project
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
// middleware.ts (next to your app/ or pages/ folder)
|
|
30
|
+
import { telemetryMiddleware } from "@adwait12345/telemetry-next";
|
|
31
|
+
import { NextResponse } from "next/server";
|
|
32
|
+
import type { NextRequest } from "next/server";
|
|
33
|
+
|
|
34
|
+
const telemetry = telemetryMiddleware({
|
|
35
|
+
projectId: "your-project-id",
|
|
36
|
+
apiUrl: "https://telemetry-uqd3.onrender.com",
|
|
37
|
+
serverSecret: "sk_...",
|
|
38
|
+
debug: false,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
export async function middleware(req: NextRequest) {
|
|
42
|
+
await telemetry(req);
|
|
43
|
+
return NextResponse.next();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const config = {
|
|
47
|
+
matcher: [
|
|
48
|
+
// Match all routes except Next.js internals and static files
|
|
49
|
+
"/((?!_next/static|_next/image|favicon.ico).*)",
|
|
50
|
+
],
|
|
51
|
+
};
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 2. Use environment variables (recommended)
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
const telemetry = telemetryMiddleware({
|
|
58
|
+
projectId: process.env.TELEMETRY_PROJECT_ID!,
|
|
59
|
+
apiUrl: process.env.TELEMETRY_API_URL,
|
|
60
|
+
serverSecret: process.env.TELEMETRY_SERVER_SECRET!,
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
# .env.local
|
|
66
|
+
TELEMETRY_PROJECT_ID=your-project-id
|
|
67
|
+
TELEMETRY_API_URL=https://telemetry-uqd3.onrender.com
|
|
68
|
+
TELEMETRY_SERVER_SECRET=sk_...
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## How it works
|
|
74
|
+
|
|
75
|
+
1. **Every request** that passes the `matcher` runs through the middleware
|
|
76
|
+
2. The request is normalized (UA, IP, headers) and passed to `detectBot()`
|
|
77
|
+
3. If a bot is detected (or `trackAll: true`), a payload is sent to the Telemetry API
|
|
78
|
+
4. On **Vercel Edge / Cloudflare Workers**, `waitUntil` is used so the send happens after the response is sent — zero latency impact
|
|
79
|
+
5. On other runtimes, the send is `await`ed before `NextResponse.next()` is returned
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Configuration options
|
|
84
|
+
|
|
85
|
+
| Option | Type | Default | Description |
|
|
86
|
+
|--------|------|---------|-------------|
|
|
87
|
+
| `projectId` | `string` | **required** | Your Telemetry project ID |
|
|
88
|
+
| `serverSecret` | `string` | **required** | Your server secret key for API auth |
|
|
89
|
+
| `apiUrl` | `string` | hosted service | Override the API endpoint |
|
|
90
|
+
| `trackAll` | `boolean` | `false` | Track all requests, not just bots |
|
|
91
|
+
| `trackSearchBots` | `boolean` | `true` | Include Googlebot, Bingbot etc. |
|
|
92
|
+
| `ignorePaths` | `(string \| RegExp)[]` | — | Paths to skip entirely |
|
|
93
|
+
| `customBots` | `Array<{name, pattern, category?}>` | — | Add custom bot definitions |
|
|
94
|
+
| `debug` | `boolean` | `false` | Log detection results to the console |
|
|
95
|
+
| `authorizationHeader` | `string` | — | Fully custom `Authorization` header value |
|
|
96
|
+
| `headers` | `Record<string, string>` | — | Extra headers on every telemetry request |
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Examples
|
|
101
|
+
|
|
102
|
+
### Skip API routes and health checks
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
telemetryMiddleware({
|
|
106
|
+
projectId: "...",
|
|
107
|
+
serverSecret: "sk_...",
|
|
108
|
+
ignorePaths: ["/health", "/ping", /^\/api\//],
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Track all visitors (not just bots)
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
telemetryMiddleware({
|
|
116
|
+
projectId: "...",
|
|
117
|
+
serverSecret: "sk_...",
|
|
118
|
+
trackAll: true,
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Add custom bot definitions
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
telemetryMiddleware({
|
|
126
|
+
projectId: "...",
|
|
127
|
+
serverSecret: "sk_...",
|
|
128
|
+
customBots: [
|
|
129
|
+
{ name: "MyInternalCrawler", pattern: /my-crawler\/\d+/i, category: "scraper" },
|
|
130
|
+
],
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## What gets tracked
|
|
137
|
+
|
|
138
|
+
Each bot detection event sends:
|
|
139
|
+
|
|
140
|
+
| Field | Description |
|
|
141
|
+
|-------|-------------|
|
|
142
|
+
| `projectId` | Your project ID |
|
|
143
|
+
| `path` | Request path |
|
|
144
|
+
| `method` | HTTP method |
|
|
145
|
+
| `userAgent` | Full user-agent string |
|
|
146
|
+
| `ip` | Client IP (from `x-forwarded-for`) |
|
|
147
|
+
| `isBot` | `true` / `false` |
|
|
148
|
+
| `botName` | Named bot e.g. `"GPTBot"`, or `null` |
|
|
149
|
+
| `botCategory` | e.g. `"ai-crawler"`, `"search"`, `"scraper"` |
|
|
150
|
+
| `confidence` | `"certain"` / `"high"` / `"medium"` / `"low"` |
|
|
151
|
+
| `detectionMethod` | `"ua-match"` / `"header-anomaly"` / `"automation-header"` / etc. |
|
|
152
|
+
| `referrer` | Referrer header |
|
|
153
|
+
| `timestamp` | ISO 8601 UTC |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adwait12345/telemetry-next",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Next.js middleware for Telemetry SDK - track AI bots and crawlers",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
"types": "./dist/index.d.ts"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
15
19
|
"dependencies": {
|
|
16
20
|
"@adwait12345/telemetry-core": ">=0.1.0"
|
|
17
21
|
},
|
package/src/index.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { ServerTrackPayload } from "@adwait12345/telemetry-core";
|
|
2
|
-
import { type NextRequest, type NextResponse } from "next/server";
|
|
3
|
-
import {
|
|
4
|
-
detectBot,
|
|
5
|
-
extractAutomationHeaders,
|
|
6
|
-
sendToTelemetry,
|
|
7
|
-
type TelemetryConfig,
|
|
8
|
-
type NormalizedRequest,
|
|
9
|
-
} from "@adwait12345/telemetry-core";
|
|
10
|
-
|
|
11
|
-
export function telemetryMiddleware(config: TelemetryConfig) {
|
|
12
|
-
return async function (req: NextRequest): Promise<void> {
|
|
13
|
-
const userAgent = req.headers.get("user-agent") || "";
|
|
14
|
-
const ip = req.ip || req.headers.get("x-forwarded-for") || "";
|
|
15
|
-
const url = new URL(req.url);
|
|
16
|
-
const path = url.pathname;
|
|
17
|
-
|
|
18
|
-
if (config.ignorePaths) {
|
|
19
|
-
for (const ignorePath of config.ignorePaths) {
|
|
20
|
-
if (typeof ignorePath === "string" && path === ignorePath) {
|
|
21
|
-
return;
|
|
22
|
-
} else if (ignorePath instanceof RegExp && ignorePath.test(path)) {
|
|
23
|
-
return;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// Convert headers to a standard object for extractAutomationHeaders
|
|
29
|
-
const headersObj: Record<string, string> = {};
|
|
30
|
-
req.headers.forEach((value, key) => {
|
|
31
|
-
headersObj[key] = value;
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
const normalizedReq: NormalizedRequest = {
|
|
35
|
-
userAgent,
|
|
36
|
-
ip: ip.split(",")[0],
|
|
37
|
-
path,
|
|
38
|
-
method: req.method,
|
|
39
|
-
referrer: req.headers.get("referer") || null,
|
|
40
|
-
acceptLanguage: req.headers.get("accept-language") || null,
|
|
41
|
-
acceptEncoding: req.headers.get("accept-encoding") || null,
|
|
42
|
-
secFetchSite: req.headers.get("sec-fetch-site") || null,
|
|
43
|
-
httpVersion: null, // Next.js middleware doesn't easily expose http version
|
|
44
|
-
automationHeaders: extractAutomationHeaders(headersObj),
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
const result = detectBot(normalizedReq, config.customBots);
|
|
48
|
-
|
|
49
|
-
const shouldTrackBot =
|
|
50
|
-
result.isBot &&
|
|
51
|
-
(config.trackSearchBots !== false || result.botCategory !== "search");
|
|
52
|
-
|
|
53
|
-
if (config.trackAll || shouldTrackBot) {
|
|
54
|
-
const payload: ServerTrackPayload = {
|
|
55
|
-
projectId: config.projectId,
|
|
56
|
-
path: normalizedReq.path,
|
|
57
|
-
method: normalizedReq.method,
|
|
58
|
-
referrer: normalizedReq.referrer,
|
|
59
|
-
userAgent: normalizedReq.userAgent,
|
|
60
|
-
ip: normalizedReq.ip,
|
|
61
|
-
isBot: result.isBot,
|
|
62
|
-
botName: result.botName,
|
|
63
|
-
botCategory: result.botCategory,
|
|
64
|
-
confidence: result.confidence,
|
|
65
|
-
detectionMethod: result.method,
|
|
66
|
-
source: "server-middleware",
|
|
67
|
-
timestamp: new Date().toISOString(),
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
// Use waitUntil if available (Vercel edge runtime), otherwise fire-and-forget
|
|
71
|
-
const sendPromise = sendToTelemetry(payload, config).catch((err: any) => {
|
|
72
|
-
if (config.debug) {
|
|
73
|
-
console.error(
|
|
74
|
-
"[Telemetry Middleware] Failed to send to telemetry:",
|
|
75
|
-
err,
|
|
76
|
-
);
|
|
77
|
-
}
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
// @ts-ignore — waitUntil is available on Vercel/Cloudflare edge runtimes
|
|
81
|
-
if (typeof globalThis !== "undefined" && (globalThis as any).waitUntil) {
|
|
82
|
-
// @ts-ignore
|
|
83
|
-
(globalThis as any).waitUntil(sendPromise);
|
|
84
|
-
} else {
|
|
85
|
-
await sendPromise;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
};
|
|
89
|
-
}
|