ezlogs-nextjs 0.1.0 → 0.1.2

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.
Files changed (43) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +98 -688
  3. package/bin/install-triggers.cjs +1 -1
  4. package/dist/actors/index.d.cts +1 -1
  5. package/dist/actors/index.d.ts +1 -1
  6. package/dist/{configuration-D9x9Gvds.d.cts → configuration-aUYgA8-h.d.cts} +20 -3
  7. package/dist/{configuration-D9x9Gvds.d.ts → configuration-aUYgA8-h.d.ts} +20 -3
  8. package/dist/db/drizzle.cjs +17 -6
  9. package/dist/db/drizzle.js +17 -6
  10. package/dist/db/prisma.cjs +271 -76
  11. package/dist/db/prisma.d.cts +38 -1
  12. package/dist/db/prisma.d.ts +38 -1
  13. package/dist/db/prisma.js +270 -77
  14. package/dist/db/supabase.cjs +17 -6
  15. package/dist/db/supabase.js +17 -6
  16. package/dist/index.cjs +459 -222
  17. package/dist/index.d.cts +2 -2
  18. package/dist/index.d.ts +2 -2
  19. package/dist/index.js +459 -222
  20. package/dist/jobs/bullmq.cjs +6 -5
  21. package/dist/jobs/bullmq.d.cts +16 -8
  22. package/dist/jobs/bullmq.d.ts +16 -8
  23. package/dist/jobs/bullmq.js +6 -5
  24. package/dist/jobs/inngest.cjs +16 -6
  25. package/dist/jobs/inngest.js +16 -6
  26. package/dist/jobs/supabase-queues.cjs +16 -6
  27. package/dist/jobs/supabase-queues.js +16 -6
  28. package/dist/jobs/trigger.cjs +16 -6
  29. package/dist/jobs/trigger.js +16 -6
  30. package/dist/jobs/upstash-workflow.cjs +16 -6
  31. package/dist/jobs/upstash-workflow.js +16 -6
  32. package/dist/nextjs-plugin/index.cjs +18 -0
  33. package/dist/nextjs-plugin/index.js +18 -0
  34. package/dist/nextjs-plugin/loader.cjs +44 -34
  35. package/dist/nextjs-plugin/loader.d.cts +10 -0
  36. package/dist/nextjs-plugin/loader.d.ts +10 -0
  37. package/dist/nextjs-plugin/loader.js +44 -34
  38. package/dist/triggers/index.cjs +43 -8
  39. package/dist/triggers/index.d.cts +7 -0
  40. package/dist/triggers/index.d.ts +7 -0
  41. package/dist/triggers/index.js +43 -8
  42. package/package.json +3 -4
  43. package/sql/postgres/00_install.sql +1 -1
package/README.md CHANGED
@@ -1,24 +1,13 @@
1
1
  # ezlogs-nextjs
2
2
 
3
- **Drop-in activity logging for Next.js.** Captures HTTP requests, database changes, Server Actions, and background jobs. Ships them to the EZLogs server as plain-English Action cards your whole team can read.
3
+ **Drop-in activity logging for Next.js.** Captures HTTP requests,
4
+ database changes, Server Actions, and background jobs. Ships them to
5
+ the EZLogs server as plain-English Action cards your whole team can
6
+ read.
4
7
 
5
- App Router, Pages Router, Server Actions (file-level and inline), Edge runtime — all supported.
6
-
7
- ---
8
-
9
- ## The Problem
10
-
11
- When someone clicks "Reset Password" in your app, a cascade of events unfolds:
12
-
13
- - HTTP requests hit your server
14
- - Database rows get updated
15
- - Background jobs are queued
16
- - Emails are sent
17
- - Sessions are invalidated
18
-
19
- Today, understanding what happened requires opening four tools, piecing together timestamps, and asking an engineer to translate stack traces into plain English.
20
-
21
- **EZLogs solves this.** Instead of scattered technical logs, you see:
8
+ Wire-format identical to the Ruby agent (`ez_logs_agent`). Same
9
+ server ingests both. App Router, Pages Router, Server Actions
10
+ (file-level and inline), Edge runtime — all supported.
22
11
 
23
12
  ```
24
13
  Password Reset — jessica@example.com
@@ -31,57 +20,23 @@ Password Reset — jessica@example.com
31
20
  Status: Completed successfully
32
21
  ```
33
22
 
34
- Your support team, PM, and CEO can read that without an engineer.
35
-
36
- ---
37
-
38
- ## What EZLogs Is (and Is NOT)
39
-
40
- **EZLogs is:**
41
-
42
- - An application-level activity log
43
- - A bridge between technical events and business understanding
44
- - Best-effort and non-blocking — never impacts your app's performance
45
- - Safe in production — fails gracefully if anything goes wrong
46
-
47
- **EZLogs is NOT:**
48
-
49
- - A monitoring tool — use Datadog, New Relic, or Vercel Analytics
50
- - A metrics platform — use your APM for request rates, p99s, etc.
51
- - An audit log — use compliance-grade tooling (PaperTrail-style) for legal requirements
52
- - A guaranteed delivery system — events may be dropped if the server is unreachable (intentional)
53
- - A replacement for debuggers — use Sentry, Bugsnag, or your IDE for code-level debugging
54
-
55
23
  ---
56
24
 
57
25
  ## Install
58
26
 
59
27
  ```bash
60
- pnpm add ezlogs-nextjs
61
- # or
62
28
  npm install ezlogs-nextjs
63
- # or
64
- bun add ezlogs-nextjs
29
+ # or: pnpm add ezlogs-nextjs / bun add ezlogs-nextjs
65
30
  ```
66
31
 
67
- **Requirements:**
32
+ Requires Node 18.17+ and Next.js 14+.
68
33
 
69
- - Node 18.17+
70
- - Next.js 14+ (App Router and Pages Router both supported)
34
+ ## Quick start
71
35
 
72
- ---
73
-
74
- ## Quick Start
75
-
76
- Five steps, ~5 minutes. After Step 5 you'll see HTTP requests, Server Actions, and background jobs flowing into the dashboard. Database `from → to` diffs are an opt-in upgrade documented in [What Gets Captured → Database Changes](#3-database-changes).
77
-
78
- ### 1. Get your API key
36
+ ### 1. Create `instrumentation.ts`
79
37
 
80
- Sign in to your EZLogs dashboard → **Settings → API Keys → Create API key**. Copy the `ezl_...` token.
81
-
82
- ### 2. Wire up `instrumentation.ts`
83
-
84
- Create `instrumentation.ts` at your project root (or `src/instrumentation.ts` if you use the `src/` layout):
38
+ At your project root (or `src/instrumentation.ts` if you use the
39
+ `src/` layout):
85
40
 
86
41
  ```ts
87
42
  import { ezlogs } from "ezlogs-nextjs";
@@ -96,21 +51,24 @@ export async function register() {
96
51
  }
97
52
  ```
98
53
 
99
- ### 3. Add the build plugin to your Next config
54
+ ### 2. Wrap your Next config
100
55
 
101
- `withEzlogsConfig(...)` is a wrapper around your existing Next.js config object. You don't add any EZLogs-specific *settings* to your Next config — every EZLogs option goes in `ezlogs.init({...})` from Step 2. The wrapper's only job is to register the build-time loaders that auto-wrap your routes and Server Actions.
56
+ `withEzlogsConfig(...)` is a transparent wrapper around your existing
57
+ config object. It doesn't add EZLogs-specific settings to your Next
58
+ config — every EZLogs option goes in `ezlogs.init({...})`. The wrapper
59
+ just registers the build-time loaders that auto-wrap your routes and
60
+ Server Actions.
102
61
 
103
- If you already have a `next.config.*` file, keep everything that's there. The placeholder comment below is where your existing options stay; if you don't have any, leave the object empty. Pick the snippet that matches the file extension you already use:
62
+ Pick the snippet matching your config file:
104
63
 
105
- **`next.config.ts` (TypeScript — Next 14+ default scaffold):**
64
+ **`next.config.ts`** (TypeScript — Next 14+ default):
106
65
 
107
66
  ```ts
108
67
  import type { NextConfig } from "next";
109
68
  import { withEzlogsConfig } from "ezlogs-nextjs/plugin";
110
69
 
111
70
  const nextConfig: NextConfig = {
112
- // ⬇ Anything you had before (or leave empty {} if this is a fresh project).
113
- // Examples: experimental: { ppr: true }, images: { domains: [...] }, etc.
71
+ // ⬇ Your existing options (or leave empty {} on a fresh project).
114
72
  };
115
73
 
116
74
  export default withEzlogsConfig(
@@ -118,662 +76,114 @@ export default withEzlogsConfig(
118
76
  ) as NextConfig;
119
77
  ```
120
78
 
121
- The cast is harmless: `withEzlogsConfig` declares a stricter `NextConfig` shape than Next.js exports. Both are runtime-compatible.
122
-
123
- <details>
124
- <summary><strong>Using <code>next.config.mjs</code> or <code>next.config.js</code> instead?</strong></summary>
125
-
126
- **`next.config.mjs` (ESM):**
79
+ **`next.config.mjs`** (ESM):
127
80
 
128
81
  ```js
129
82
  import { withEzlogsConfig } from "ezlogs-nextjs/plugin";
130
-
131
- /** @type {import('next').NextConfig} */
132
- const nextConfig = {
133
- // ⬇ Anything you had before (or leave empty {} if this is a fresh project).
134
- };
135
-
83
+ const nextConfig = { /* your options */ };
136
84
  export default withEzlogsConfig(nextConfig);
137
85
  ```
138
86
 
139
- **`next.config.js` (CommonJS):**
87
+ **`next.config.js`** (CommonJS):
140
88
 
141
89
  ```js
142
90
  const { withEzlogsConfig } = require("ezlogs-nextjs/plugin");
143
-
144
- module.exports = withEzlogsConfig({
145
- // ⬇ Anything you had before (or leave empty {} if this is a fresh project).
146
- });
91
+ module.exports = withEzlogsConfig({ /* your options */ });
147
92
  ```
148
93
 
149
- </details>
150
-
151
- This is what makes capture **zero-touch.** The plugin auto-wraps:
152
-
153
- - App Router route handlers (`app/**/route.{ts,tsx,js,jsx}`)
154
- - Pages Router API routes (`pages/api/**/*.{ts,tsx,js,jsx}`)
155
- - File-level Server Actions (`actions.ts`, `app/**/actions.{ts,tsx}`, `actions/**/*`)
156
- - **Inline `"use server"` actions** declared inside RSC components (page/layout/etc.)
157
- - NextAuth-style local-aliased re-export routes (`export { handler as GET, POST }`)
158
- - Your root `middleware.ts` (for correlation seeding)
159
-
160
- No per-route opt-in. No source file edits.
161
-
162
- ### 4. Set environment variables
94
+ ### 3. Set env vars, restart, verify
163
95
 
164
96
  ```bash
165
- # .env.local (or your platform's secret manager)
97
+ # .env.local
98
+ EZLOGS_SERVER_URL=https://app.ezlogs.io
166
99
  EZLOGS_PROJECT_TOKEN=ezl_your_api_key_here
167
- # EZLOGS_SERVER_URL defaults to https://app.ezlogs.io — set only if self-hosting.
168
- ```
169
-
170
- ### 5. Restart and verify
171
-
172
- Restart your dev server. Hit any route. Within seconds, the activity appears in your EZLogs dashboard.
173
-
174
- You'll also see startup logs in the terminal:
175
-
176
- ```
177
- [ezlogs] FlushScheduler started (interval 3000ms)
178
- ```
179
-
180
- ---
181
-
182
- ## What Gets Captured
183
-
184
- Four event sources. All four carry a shared `correlation_id` when they happen inside the same inbound request, so the EZLogs server stitches them into a single Action card.
185
-
186
- ### 1. HTTP Requests
187
-
188
- Every Route Handler call, with intelligent noise filtering.
189
-
190
- **What's captured:**
191
-
192
- - Method, path, status code, duration
193
- - GraphQL operation name + type (queries, mutations, subscriptions)
194
- - Request parameters (sanitized automatically)
195
- - Correlation ID
196
-
197
- **Automatic exclusions (no config needed):**
198
-
199
- - `/_next/*`, `/_vercel/*`, `/__nextjs_*` — bundler / platform internals
200
- - `GET /api/auth/*` — NextAuth session-refresh polls (POSTs are captured)
201
- - `/health*`, `/api/health`, `/up`, `/alive`, `/ready`, `/metrics`
202
- - `/favicon.ico`, `/.well-known*`, `/robots.txt`, `/sitemap.xml`
203
- - `*/login*`, `*/logout*`, `*/sign-in*`, `*/sign-out*`, `*/session*`
204
- - Static assets (`.js`, `.css`, `.png`, …)
205
-
206
- ### 2. Server Actions
207
-
208
- Both file-level and inline declarations. **Auto-wrapped at build time** by the loader — no manual `captureServerAction` calls required.
209
-
210
- **File-level** (file starts with `"use server"`):
211
-
212
- ```ts
213
- // app/actions.ts
214
- "use server";
215
-
216
- export async function updateProfile(formData: FormData) {
217
- await db.users.update(/* ... */);
218
- }
219
100
  ```
220
101
 
221
- **Inline** (declared inside an RSC component):
102
+ Restart your dev server, hit any route, and watch for
103
+ `[ezlogs] FlushScheduler started` in the terminal. Events appear in
104
+ your EZLogs dashboard within a few seconds.
222
105
 
223
- ```tsx
224
- // app/posts/[id]/page.tsx
225
- export default async function Post({ params }) {
226
- const { id } = await params;
106
+ ### 4. (Optional) Full DB diffs on Postgres
227
107
 
228
- async function deletePost() {
229
- "use server";
230
- await db.posts.delete({ where: { id } });
231
- redirect("/posts");
232
- }
233
-
234
- return <form action={deletePost}>{/* ... */}</form>;
235
- }
236
- ```
237
-
238
- Both produce the same `Server Action` event with actor, correlation, and `redirect()` / `notFound()` handled as success.
239
-
240
- If you need manual control (e.g., aliased imports, non-standard file layouts):
241
-
242
- ```ts
243
- import { captureServerAction } from "ezlogs-nextjs";
244
-
245
- export const updateProfile = captureServerAction(
246
- async (formData: FormData) => {
247
- /* ... */
248
- },
249
- "updateProfile",
250
- );
251
- ```
252
-
253
- ### 3. Database Changes
254
-
255
- Two paths. Pick the one that fits your stack. Both emit the same `database_callback` event.
256
-
257
- **Recommended: row triggers (Postgres).** If your app talks to Postgres directly (Prisma with `@prisma/adapter-pg`, Drizzle node-postgres, raw `pg`), this gives you **real from→to diffs** without per-mutation boilerplate.
108
+ One command installs Postgres triggers that capture every business-
109
+ table write with full from→to change diffs:
258
110
 
259
111
  ```bash
260
- # One-time install (per database). Reads DATABASE_URL from env.
261
112
  npx ezlogs-nextjs install-triggers
262
113
  ```
263
114
 
264
- That single command introspects your schema and tracks every business table automatically. Migration tables (`_prisma_migrations`, `schema_migrations`), session tables (`Session`, `sessions`), and the agent's own audit table are skipped — you'll see exactly what's tracked in the output. Pass `--tables=<a,b,c>` for an explicit list, `--tables=none` to install infrastructure only, or `--print` to dump the SQL without applying.
265
-
266
- Wire it up in `instrumentation.ts`:
267
-
268
- ```ts
269
- import { ezlogs } from "ezlogs-nextjs";
270
-
271
- export async function register() {
272
- if (process.env.NEXT_RUNTIME !== "nodejs") return;
273
- const pg = await import("pg");
274
- const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
275
- ezlogs.init({
276
- serverUrl: process.env.EZLOGS_SERVER_URL!,
277
- projectToken: process.env.EZLOGS_PROJECT_TOKEN!,
278
- databaseReader: (sql, params) => pool.query(sql, params),
279
- patchDatabaseClient: pg, // auto-injects SET LOCAL on every query
280
- });
281
- }
282
- ```
283
-
284
- Your existing `prisma.post.create(...)` / `db.update(users)...` / `pool.query("INSERT ...")` calls now produce full-fidelity events with actor + correlation + diffs.
285
-
286
- **Fallback: per-ORM adapters.** When the trigger path isn't viable (PlanetScale, supabase-js, customers who can't run the migration), adapters keep working with reduced fidelity (writes captured, but Drizzle gives no pre-state, Prisma's `$extends` gives only `to`, and supabase-js multi-`.eq()` filters drop `from`):
287
-
288
- - **Prisma** — `import { ezlogsPrisma } from "ezlogs-nextjs/prisma"`
289
- - **Drizzle** — `import { ezlogsDrizzleLogger } from "ezlogs-nextjs/drizzle"`
290
- - **Supabase** — `import { wrapSupabase } from "ezlogs-nextjs/supabase"`
291
-
292
- ### 4. Background Jobs
293
-
294
- Five runners. Pick the one(s) you use. All emit the same `background_job` event.
295
-
296
- | Runner | Import |
297
- |---|---|
298
- | BullMQ | `ezlogs-nextjs/bullmq` |
299
- | Inngest | `ezlogs-nextjs/inngest` |
300
- | Trigger.dev | `ezlogs-nextjs/trigger` |
301
- | Supabase Queues (pgmq) | `ezlogs-nextjs/supabase-queues` |
302
- | Upstash Workflow / QStash | `ezlogs-nextjs/upstash-workflow` |
303
-
304
- Example (BullMQ):
305
-
306
- ```ts
307
- import { Queue, Worker } from "bullmq";
308
- import { wrapBullQueue, wrapBullWorker } from "ezlogs-nextjs/bullmq";
309
-
310
- export const queue = wrapBullQueue(new Queue("emails"));
311
- export const worker = wrapBullWorker(new Worker("emails", processor));
312
- ```
313
-
314
- See the [adapter sections below](#background-job-adapters) for the full surface.
315
-
316
- ---
317
-
318
- ## Auth (Actor Extraction)
319
-
320
- EZLogs tracks **who** triggered each action. Built-in extractors for the four most common Next.js auth providers, lazy-imported so apps that don't use a given provider pay nothing at runtime.
321
-
322
- ### Clerk
323
-
324
- ```ts
325
- import { clerkActor } from "ezlogs-nextjs/actors";
326
-
327
- ezlogs.init({
328
- // ...
329
- actorFromRequest: clerkActor(),
330
- });
331
- ```
332
-
333
- ### NextAuth.js (v4)
334
-
335
- ```ts
336
- import { nextAuthActor } from "ezlogs-nextjs/actors";
337
- import { authOptions } from "@/lib/auth";
338
-
339
- ezlogs.init({
340
- // ...
341
- actorFromRequest: nextAuthActor({ authOptions }),
342
- });
343
- ```
344
-
345
- ### Auth.js (v5)
346
-
347
- ```ts
348
- import { authJsActor } from "ezlogs-nextjs/actors";
349
- import { auth } from "@/auth";
350
-
351
- ezlogs.init({
352
- // ...
353
- actorFromRequest: authJsActor({ auth }),
354
- });
355
- ```
356
-
357
- ### Supabase Auth
358
-
359
- No opt-in needed. The agent resolves the current user via `auth.getUser()` automatically once any Supabase client is wrapped.
360
-
361
- ### Custom / Composing
362
-
363
- ```ts
364
- actorFromRequest: async (request) => {
365
- // Try multiple providers, return first match
366
- return (
367
- (await clerkActor()(request)) ??
368
- (await nextAuthActor({ authOptions })(request))
369
- );
370
- }
371
- ```
372
-
373
- The hook returns `{ id: string, label?: string }` or `null`. **Missing data is acceptable; wrong data is not** — the agent never guesses.
115
+ Migration tables, sessions, and the agent's own audit table are
116
+ skipped automatically. Without this, the agent still captures DB
117
+ writes via per-ORM adapters — you just lose the from-value half of
118
+ each change. See [docs/database.md](./docs/database.md) for trade-offs.
374
119
 
375
120
  ---
376
121
 
377
- ## Configuration Reference
378
-
379
- All options have sensible defaults. **Only `serverUrl` and `projectToken` are required.**
380
-
381
- ### Minimal
382
-
383
- ```ts
384
- ezlogs.init({
385
- projectToken: "ezl_your_api_key_here",
386
- // serverUrl defaults to "https://app.ezlogs.io" — set only when self-hosting.
387
- });
388
- ```
389
-
390
- ### Full surface
391
-
392
- ```ts
393
- ezlogs.init({
394
- // ==========================================
395
- // Required
396
- // ==========================================
397
- projectToken: "ezl_your_api_key_here",
398
-
399
- // ==========================================
400
- // Optional — defaults to the hosted EZLogs service
401
- // ==========================================
402
- serverUrl: "https://app.ezlogs.io",
403
-
404
- // ==========================================
405
- // Event capture toggles (all default true)
406
- // ==========================================
407
- captureHttp: true,
408
- captureDb: true,
409
- captureJobs: true,
410
-
411
- // ==========================================
412
- // Pipeline tuning (defaults match the Ruby agent)
413
- // ==========================================
414
- bufferSize: 10_000, // events held in memory (drop-oldest when full)
415
- sendInterval: 3_000, // ms between automatic flushes
416
- retryAttempts: 3, // exponential backoff: 0.5s → 1s → 2s → 4s (capped at 5s), with ±20% jitter
417
-
418
- // ==========================================
419
- // Exclusion lists (MERGED with built-in defaults)
420
- // ==========================================
421
- excludedPaths: ["/admin/preview*", "/internal/*"],
422
- excludedTables: ["audit_logs", "versions"],
423
- excludedJobClasses: ["app/internal/heartbeat"],
424
- excludedGraphqlOperations: ["IntrospectionQuery"],
425
- excludedGraphqlVariableKeys: ["password", "creditCard"],
426
-
427
- // ==========================================
428
- // Actor (who triggered the event)
429
- // ==========================================
430
- actorFromRequest: clerkActor(), // or custom (request) => {...}
431
-
432
- // ==========================================
433
- // Display names (human-readable resource labels)
434
- // ==========================================
435
- displayNameFor: {
436
- User: "email", // "User created 'jessica@example.com'"
437
- Order: "number", // "Order updated '#ORD-1234'"
438
- Product: "name", // "Product deleted 'Premium Plan'"
439
- },
440
-
441
- // ==========================================
442
- // Database triggers (Postgres only, recommended)
443
- // ==========================================
444
- databaseReader: (sql, params) => pool.query(sql, params),
445
- patchDatabaseClient: pg, // require('pg') module
446
-
447
- // ==========================================
448
- // Server Action failure classification
449
- // ==========================================
450
- isServerActionError: (result) => {
451
- // Built-ins handle next-safe-action, zsa, Conform, Zod safeParse,
452
- // and `{success: false}` shapes. Override here if needed.
453
- if (result?.code === "VALIDATION_FAILED") return { errorMessage: result.message };
454
- return null;
455
- },
456
-
457
- // ==========================================
458
- // Outgoing fetch correlation injection (default true)
459
- // ==========================================
460
- patchGlobalFetch: true, // patches globalThis.fetch to add X-Correlation-ID
461
-
462
- // ==========================================
463
- // Logging
464
- // ==========================================
465
- logLevel: "info", // "debug" | "info" | "warn" | "error" | "silent"
466
- });
467
- ```
468
-
469
- Defaults and recommended overrides are covered in [Configuration Reference](#configuration-reference) above and [Troubleshooting](#troubleshooting) below.
470
-
471
- ---
472
-
473
- ## How Correlation Works
474
-
475
- Events are linked together using a `correlation_id`, so EZLogs can reconstruct the complete chain triggered by a single user action:
122
+ ## What gets captured
476
123
 
477
- ```
478
- HTTP Request
479
- └─ generates correlation_id: "ezl_1736812345_8a3f9b2c"
480
- ├─ Database INSERT (inherits "ezl_...")
481
- ├─ Server Action: createPost (inherits "ezl_...")
482
- │ └─ Database INSERT (inherits "ezl_...")
483
- └─ Background Job enqueue (inherits "ezl_...")
484
- └─ Job execution (inherits "ezl_...")
485
- └─ Database UPDATE (inherits "ezl_...")
486
- ```
487
-
488
- **Zero configuration required.** Propagation works via:
489
-
490
- - Request headers (`X-Ezlogs-Correlation-ID`)
491
- - AsyncLocalStorage (Node runtime)
492
- - Platform fallbacks (`x-vercel-id`, `cf-ray`, `x-request-id`) for apps without `middleware.ts`
493
- - Postgres `SET LOCAL` on the wrapped connection (when using `patchDatabaseClient`)
494
- - Job-runner metadata for BullMQ / Inngest / Trigger.dev / QStash
495
-
496
- **Best-effort, not guaranteed.** Some events have no correlation:
497
-
498
- - Cron-triggered jobs
499
- - Console operations
500
- - Cross-process job chains across cold-started serverless functions (unless platform IDs match)
501
-
502
- That's fine. Events still get captured — they just appear as separate Actions.
503
-
504
- ---
505
-
506
- ## Auto-Wrap Coverage (Build Plugin)
507
-
508
- The build plugin (`withEzlogsConfig`) auto-wraps these file patterns at build time. Both Webpack and Turbopack are supported.
509
-
510
- | Pattern | Loader kind | What it wraps |
124
+ | Source | What | Where it comes from |
511
125
  |---|---|---|
512
- | `app/**/route.{ts,tsx,js,jsx}` | `app-route-handler` | App Router route handlers (GET/POST/etc.) |
513
- | `pages/api/**/*.{ts,tsx,js,jsx}` | `pages-api` | Pages Router API routes |
514
- | `middleware.{ts,tsx,js,jsx}` (root + `src/`) | `middleware` | Your `middleware.ts` (correlation seeding) |
515
- | `actions/**/*`, `app/**/actions.{ts,tsx}`, `app/**/actions/**/*` | `server-action` | File-level `"use server"` modules |
516
- | `app/**/{page,layout,template,loading,error,default,not-found}.{ts,tsx,js,jsx}` | `inline-server-action` | Inline `"use server"` actions inside RSC components (gated on content) |
517
- | `lib/supabase/**`, `utils/supabase/**` (+ `src/` variants) | `supabase-factory` | Rewrites Supabase factory imports to auto-instrument every client |
518
-
519
- **Files outside these conventional locations** that use `"use server"` won't be auto-wrapped. Wrap manually with `captureServerAction(fn, "name")` or move the file under `actions/`.
520
-
521
- The plugin is idempotent and safe to re-run. The loader fast-paths files that don't contain `"use server"` so unrelated route files pay zero overhead.
522
-
523
- ---
524
-
525
- ## Background Job Adapters
526
-
527
- ### BullMQ
528
-
529
- ```ts
530
- import { Queue, Worker } from "bullmq";
531
- import { wrapBullQueue, wrapBullWorker } from "ezlogs-nextjs/bullmq";
532
-
533
- export const queue = wrapBullQueue(new Queue("emails"));
534
- export const worker = wrapBullWorker(new Worker("emails", processor));
535
- ```
536
-
537
- ### Inngest
538
-
539
- ```ts
540
- import { Inngest } from "inngest";
541
- import { ezlogsInngestMiddleware } from "ezlogs-nextjs/inngest";
542
-
543
- export const inngest = new Inngest({
544
- id: "my-app",
545
- middleware: [ezlogsInngestMiddleware()],
546
- });
547
- ```
548
-
549
- ### Trigger.dev
550
-
551
- ```ts
552
- // trigger/init.ts — call once at task-runtime startup
553
- import { tasks } from "@trigger.dev/sdk/v3";
554
- import { registerTriggerHooks } from "ezlogs-nextjs/trigger";
555
-
556
- registerTriggerHooks(tasks);
557
- ```
558
-
559
- ### Supabase Queues (pgmq)
560
-
561
- ```ts
562
- import { createClient } from "@supabase/supabase-js";
563
- import {
564
- wrapSupabaseQueueClient,
565
- captureQueueMessage,
566
- } from "ezlogs-nextjs/supabase-queues";
567
-
568
- const supabase = wrapSupabaseQueueClient(createClient(url, key));
569
-
570
- // Enqueue: correlation stamped automatically
571
- await supabase.schema("pgmq_public").rpc("send", {
572
- queue_name: "emails",
573
- message: { to: "alice@example.com" },
574
- });
575
-
576
- // Worker: wrap each message
577
- await captureQueueMessage(
578
- { queueName: "emails", messageId: row.msg_id, message: row.message },
579
- async () => {
580
- /* ... process the message ... */
581
- },
582
- );
583
- ```
584
-
585
- ### Upstash Workflow / QStash
586
-
587
- ```ts
588
- import { Client } from "@upstash/qstash";
589
- import { serve } from "@upstash/workflow/nextjs";
590
- import {
591
- wrapQStashClient,
592
- captureWorkflowRequest,
593
- } from "ezlogs-nextjs/upstash-workflow";
594
-
595
- export const qstash = wrapQStashClient(new Client({ token: process.env.QSTASH_TOKEN! }));
596
-
597
- export const { POST } = serve(async (context) => {
598
- await captureWorkflowRequest(
599
- { request: context.request, workflowName: "send-welcome" },
600
- async () => {
601
- await context.run("send-email", async () => {
602
- /* ... */
603
- });
604
- },
605
- );
606
- });
607
- ```
608
-
609
- ---
610
-
611
- ## Serverless / Vercel
612
-
613
- The agent auto-detects Vercel, AWS Lambda, Netlify Functions, and Cloudflare Pages. In serverless mode, `captureRoute` flushes synchronously after each handler resolves so events ship before the function freezes.
614
-
615
- For runtimes the auto-detect doesn't recognize, call `await ezlogs.flush()` before your handler returns:
616
-
617
- ```ts
618
- import { ezlogs, captureRoute } from "ezlogs-nextjs";
619
-
620
- export const POST = captureRoute(async (request) => {
621
- /* ... your handler ... */
622
- await ezlogs.flush();
623
- return Response.json({ ok: true });
624
- });
625
- ```
626
-
627
- ---
628
-
629
- ## Safety Guarantees
630
-
631
- The agent is designed to be **invisible** to your application. It will never be the reason your app fails.
632
-
633
- - **Never throws** into the host application — every public surface wraps its work in `try/catch`
634
- - **Never blocks** requests, Server Actions, or jobs — sending is async on a background flush scheduler
635
- - **Buffer overflow** — drops oldest events when full (default `bufferSize: 10000`)
636
- - **Network failures** — exponential backoff with jitter, gives up gracefully after `retryAttempts`
637
- - **Build failures** — the loader try-catches the entire parse + transform; any error returns source unchanged with a `console.warn`
638
- - **Graceful shutdown** — flushes remaining events on `beforeExit` (Node) and Vercel `after()` (serverless)
639
-
640
- **Design principle:** Your application's reliability is more important than capturing every event. EZLogs is best-effort, not guaranteed delivery.
641
-
642
- ---
643
-
644
- ## Troubleshooting
645
-
646
- ### No events showing up
647
-
648
- 1. **Confirm the agent initialized.** Look for this in your dev-server logs:
649
-
650
- ```
651
- [ezlogs] FlushScheduler started (interval 3000ms)
652
- ```
653
-
654
- If absent, `ezlogs.init` didn't run — check `instrumentation.ts` is at the project root (or `src/`) and that `process.env.NEXT_RUNTIME === "nodejs"` is true.
655
-
656
- 2. **Enable debug logging:**
657
-
658
- ```ts
659
- ezlogs.init({
660
- // ...
661
- logLevel: "debug",
662
- });
663
- ```
664
-
665
- Restart and watch for `[ezlogs] Transport send succeeded (202)` after each request.
666
-
667
- 3. **Verify network connectivity:**
668
-
669
- ```bash
670
- curl -I $EZLOGS_SERVER_URL
671
- ```
672
-
673
- ### `Module not found: Can't resolve './page.tsx.tsx'`
674
-
675
- Turbopack path-doubling bug. The agent guards against this on its own rules, but if you've customized `next.config.js` with your own `turbopack.rules`, narrow your rule's content condition or scope.
676
-
677
- ### Auth events not captured
678
-
679
- `/api/auth/*` is excluded by default for **GET / HEAD only** (NextAuth's session-refresh polls would flood your dashboard). POST callbacks — sign-in, sign-out, register — are captured. If you've added your own exclusion that covers `POST`, remove it.
680
-
681
- ### Inline `"use server"` action not captured
682
-
683
- The auto-wrap only fires on Next's conventional route filenames: `page`, `layout`, `template`, `loading`, `error`, `default`, `not-found`. If your inline action lives elsewhere, either move it or wrap manually with `captureServerAction`.
684
-
685
- ### Authentication errors (HTTP 401)
686
-
687
- 1. Verify your API key in the EZLogs dashboard under **Settings → API Keys**.
688
- 2. Check for extra whitespace in `projectToken`: `"ezl_abc123"` not `" ezl_abc123 "`.
689
- 3. Confirm the key hasn't been revoked.
690
-
691
- ### Events appearing late
692
-
693
- Normal. Events flush every 3 seconds by default. To reduce latency at the cost of more network calls, set `sendInterval: 1000`.
694
-
695
- ### Buffer warnings
696
-
697
- ```
698
- [ezlogs] Buffer full, dropping oldest event
699
- ```
700
-
701
- Your app generates events faster than they can be sent. Increase `bufferSize` or `sendInterval`, or disable a noisy capture type (`captureDb: false` in a write-heavy app).
702
-
703
- ---
704
-
705
- ## How It Works
706
-
707
- ```
708
- Your Next.js Application
709
- │
710
- ├─ HTTP Request → Route Handler (auto-wrapped at build time)
711
- │ └─ captureRoute opens correlation + actor scope
712
- │ └─ event added to Buffer
713
- │
714
- ├─ Server Action → file-level or inline (auto-wrapped at build time)
715
- │ └─ captureServerAction opens correlation + actor scope
716
- │ └─ event added to Buffer
717
- │
718
- ├─ Database mutation → Prisma / Drizzle / supabase-js / raw pg
719
- │ └─ Postgres trigger writes ezlogs_audit_log row
720
- │ └─ flushAuditLog reader emits database_callback events
721
- │ └─ events added to Buffer
722
- │
723
- └─ Background job → BullMQ / Inngest / Trigger.dev / pgmq / QStash
724
- └─ adapter middleware captures job lifecycle
725
- └─ event added to Buffer
726
- │
727
- ▼
728
- ┌──────────────────┐
729
- │ Buffer │ thread-safe, in-memory, drop-oldest
730
- │ 10,000 events │
731
- └──────────────────┘
732
- │
733
- ▼
734
- ┌──────────────────┐
735
- │ FlushScheduler │ background, every 3s
736
- └──────────────────┘
737
- │
738
- ▼
739
- ┌──────────────────┐
740
- │ Transport │ POST /api/events with bearer auth
741
- │ │ retry: 0.5s → 1s → 2s → 4s (capped at 5s), jittered
742
- └──────────────────┘
743
- │
744
- ▼
745
- ┌──────────────────┐
746
- │ EZLogs Server │ groups events into Action cards
747
- └──────────────────┘
748
- ```
749
-
750
- **Key points:**
751
-
752
- - Capture is **synchronous and microsecond-cheap** — no blocking on the request path
753
- - Sending is **asynchronous** via the FlushScheduler
754
- - Buffer is **circular** — oldest events are dropped when full
755
- - Transport uses **exponential backoff with jitter** (1 initial + 3 retries by default, then drops) — safe for serverless thundering-herd
756
-
757
- ---
758
-
759
- ## Status
760
-
761
- - **671 unit + integration tests**, all green
762
- - **Wire-format parity-tested** against the Ruby agent's fixtures (every event shape byte-for-byte identical)
763
- - **Live-validated** on 3 production-shaped Next.js stacks: Next 16 + supabase-js, Next 15 + Drizzle (postgres-js), Next 16 + Prisma + NextAuth
764
- - **Defensive:** every public surface wraps its work in `try/catch` and logs failures — the agent never throws back into your code
765
-
766
- ---
126
+ | HTTP | Method, path, status, duration, sanitized params, GraphQL op | App Router + Pages Router (auto-wrapped) |
127
+ | Server Actions | Action name, args, outcome, redirect/notFound handled as success | File-level + inline `"use server"` (auto-wrapped) |
128
+ | Database | `model_class`, `operation`, full from→to diffs (trigger path) | Postgres triggers, Prisma, Drizzle, supabase-js |
129
+ | Background jobs | `job_class`, `job_id`, `queue`, `retry_count` | BullMQ, Inngest, Trigger.dev, pgmq, Upstash Workflow |
130
+
131
+ Every event in one inbound request shares a `correlation_id` so the
132
+ server stitches them into a single Action card.
133
+
134
+ **Automatic exclusions** (no config needed):
135
+ `_next`, `_vercel`, `__nextjs_*`, `GET /api/auth/*` (NextAuth session
136
+ polls), health-checks, login / logout / session paths, static assets.
137
+ POSTs on `/api/auth/*` are captured (sign-in, sign-out, register).
138
+
139
+ ## Per-area docs
140
+
141
+ - [docs/auth.md](./docs/auth.md) — actor extraction (Clerk, NextAuth,
142
+ Auth.js, Supabase)
143
+ - [docs/database.md](./docs/database.md) — trigger path, per-ORM
144
+ adapters, sensitive-column filter
145
+ - [docs/jobs.md](./docs/jobs.md) — five background-job runners
146
+ - [docs/configuration.md](./docs/configuration.md) — every option,
147
+ defaults, auto-wrap coverage, correlation flow
148
+ - [docs/troubleshooting.md](./docs/troubleshooting.md) — common
149
+ failures and how to diagnose them
150
+ - [AGENT_PARITY_NOTES.md](./AGENT_PARITY_NOTES.md) — every intentional
151
+ deviation between this agent and the Ruby agent (`ez_logs_agent`)
152
+
153
+ ## Safety guarantees
154
+
155
+ The agent is designed to be **invisible** to your application.
156
+
157
+ - **Never throws** into the host — every public surface wraps its work
158
+ in `try/catch`.
159
+ - **Never blocks** requests — sending is asynchronous on a background
160
+ flush scheduler.
161
+ - **Build-safe** — the build-time loader wraps every transform in
162
+ try/catch and returns source unchanged on any error, so a regression
163
+ in the loader can't break `next build`.
164
+ - **Bounded** — buffer drops oldest events when full (default 10k).
165
+ - **Read-only by design** — the agent never writes back into your app.
166
+ No webhooks, no quotas enforced from EZLogs settings, no MCP
167
+ write-tools.
168
+
169
+ Your application's reliability is more important than capturing every
170
+ event. EZLogs is best-effort, not guaranteed delivery.
171
+
172
+ ## Wire-format parity
173
+
174
+ The Node agent emits byte-identical events to the Ruby agent
175
+ (`ez_logs_agent`). The parity test
176
+ (`tests/parity/event-builder.parity.test.ts`) is the contract — see
177
+ [AGENT_PARITY_NOTES.md](./AGENT_PARITY_NOTES.md) for the full list of
178
+ guarantees and the few intentional deviations (different default
179
+ exclusion lists, Node-only serverless flush mode).
767
180
 
768
181
  ## License
769
182
 
770
- MIT. See [LICENSE](./LICENSE).
771
-
772
- ---
183
+ MIT.
773
184
 
774
185
  ## Support
775
186
 
776
- - **Issues:** [github.com/dezsirazvan/ez_logs_agent_nextjs/issues](https://github.com/dezsirazvan/ez_logs_agent_nextjs/issues)
777
- - **Email:** support@ezlogs.io
187
+ Issues and questions: [github.com/dezsirazvan/ez_logs_agent_nextjs/issues](https://github.com/dezsirazvan/ez_logs_agent_nextjs/issues)
778
188
 
779
- **Made for everyone on your team, not just engineers.**
189
+ Email: support@ezlogs.io