ezlogs-nextjs 0.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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +779 -0
  3. package/bin/install-triggers.cjs +75 -0
  4. package/dist/actors/index.cjs +111 -0
  5. package/dist/actors/index.d.cts +52 -0
  6. package/dist/actors/index.d.ts +52 -0
  7. package/dist/actors/index.js +107 -0
  8. package/dist/configuration-D9x9Gvds.d.cts +190 -0
  9. package/dist/configuration-D9x9Gvds.d.ts +190 -0
  10. package/dist/db/drizzle.cjs +898 -0
  11. package/dist/db/drizzle.d.cts +68 -0
  12. package/dist/db/drizzle.d.ts +68 -0
  13. package/dist/db/drizzle.js +893 -0
  14. package/dist/db/prisma.cjs +826 -0
  15. package/dist/db/prisma.d.cts +3 -0
  16. package/dist/db/prisma.d.ts +3 -0
  17. package/dist/db/prisma.js +824 -0
  18. package/dist/db/supabase.cjs +1027 -0
  19. package/dist/db/supabase.d.cts +32 -0
  20. package/dist/db/supabase.d.ts +32 -0
  21. package/dist/db/supabase.js +1024 -0
  22. package/dist/index.cjs +3329 -0
  23. package/dist/index.d.cts +305 -0
  24. package/dist/index.d.ts +305 -0
  25. package/dist/index.js +3317 -0
  26. package/dist/jobs/bullmq.cjs +624 -0
  27. package/dist/jobs/bullmq.d.cts +33 -0
  28. package/dist/jobs/bullmq.d.ts +33 -0
  29. package/dist/jobs/bullmq.js +621 -0
  30. package/dist/jobs/inngest.cjs +645 -0
  31. package/dist/jobs/inngest.d.cts +21 -0
  32. package/dist/jobs/inngest.d.ts +21 -0
  33. package/dist/jobs/inngest.js +642 -0
  34. package/dist/jobs/supabase-queues.cjs +661 -0
  35. package/dist/jobs/supabase-queues.d.cts +37 -0
  36. package/dist/jobs/supabase-queues.d.ts +37 -0
  37. package/dist/jobs/supabase-queues.js +657 -0
  38. package/dist/jobs/trigger.cjs +622 -0
  39. package/dist/jobs/trigger.d.cts +46 -0
  40. package/dist/jobs/trigger.d.ts +46 -0
  41. package/dist/jobs/trigger.js +619 -0
  42. package/dist/jobs/upstash-workflow.cjs +673 -0
  43. package/dist/jobs/upstash-workflow.d.cts +57 -0
  44. package/dist/jobs/upstash-workflow.d.ts +57 -0
  45. package/dist/jobs/upstash-workflow.js +669 -0
  46. package/dist/nextjs-plugin/index.cjs +232 -0
  47. package/dist/nextjs-plugin/index.d.cts +68 -0
  48. package/dist/nextjs-plugin/index.d.ts +68 -0
  49. package/dist/nextjs-plugin/index.js +229 -0
  50. package/dist/nextjs-plugin/loader.cjs +16248 -0
  51. package/dist/nextjs-plugin/loader.d.cts +61 -0
  52. package/dist/nextjs-plugin/loader.d.ts +61 -0
  53. package/dist/nextjs-plugin/loader.js +16242 -0
  54. package/dist/triggers/index.cjs +1354 -0
  55. package/dist/triggers/index.d.cts +243 -0
  56. package/dist/triggers/index.d.ts +243 -0
  57. package/dist/triggers/index.js +1337 -0
  58. package/package.json +150 -0
  59. package/sql/postgres/00_install.sql +205 -0
package/README.md ADDED
@@ -0,0 +1,779 @@
1
+ # ezlogs-nextjs
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.
4
+
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:
22
+
23
+ ```
24
+ Password Reset — jessica@example.com
25
+ 2:23 PM, January 15, 2026
26
+
27
+ ✓ Reset link created (expires in 1 hour)
28
+ ✓ Email sent to jessica@example.com
29
+ ✓ All active sessions logged out (2 devices)
30
+
31
+ Status: Completed successfully
32
+ ```
33
+
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
+ ---
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pnpm add ezlogs-nextjs
61
+ # or
62
+ npm install ezlogs-nextjs
63
+ # or
64
+ bun add ezlogs-nextjs
65
+ ```
66
+
67
+ **Requirements:**
68
+
69
+ - Node 18.17+
70
+ - Next.js 14+ (App Router and Pages Router both supported)
71
+
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
79
+
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):
85
+
86
+ ```ts
87
+ import { ezlogs } from "ezlogs-nextjs";
88
+
89
+ export async function register() {
90
+ if (process.env.NEXT_RUNTIME === "nodejs") {
91
+ ezlogs.init({
92
+ serverUrl: process.env.EZLOGS_SERVER_URL!,
93
+ projectToken: process.env.EZLOGS_PROJECT_TOKEN!,
94
+ });
95
+ }
96
+ }
97
+ ```
98
+
99
+ ### 3. Add the build plugin to your Next config
100
+
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.
102
+
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:
104
+
105
+ **`next.config.ts` (TypeScript — Next 14+ default scaffold):**
106
+
107
+ ```ts
108
+ import type { NextConfig } from "next";
109
+ import { withEzlogsConfig } from "ezlogs-nextjs/plugin";
110
+
111
+ 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.
114
+ };
115
+
116
+ export default withEzlogsConfig(
117
+ nextConfig as unknown as Parameters<typeof withEzlogsConfig>[0],
118
+ ) as NextConfig;
119
+ ```
120
+
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):**
127
+
128
+ ```js
129
+ 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
+
136
+ export default withEzlogsConfig(nextConfig);
137
+ ```
138
+
139
+ **`next.config.js` (CommonJS):**
140
+
141
+ ```js
142
+ 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
+ });
147
+ ```
148
+
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
163
+
164
+ ```bash
165
+ # .env.local (or your platform's secret manager)
166
+ 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
+ ```
220
+
221
+ **Inline** (declared inside an RSC component):
222
+
223
+ ```tsx
224
+ // app/posts/[id]/page.tsx
225
+ export default async function Post({ params }) {
226
+ const { id } = await params;
227
+
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.
258
+
259
+ ```bash
260
+ # One-time install (per database). Reads DATABASE_URL from env.
261
+ npx ezlogs-nextjs install-triggers
262
+ ```
263
+
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.
374
+
375
+ ---
376
+
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:
476
+
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 |
511
+ |---|---|---|
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
+ ---
767
+
768
+ ## License
769
+
770
+ MIT. See [LICENSE](./LICENSE).
771
+
772
+ ---
773
+
774
+ ## Support
775
+
776
+ - **Issues:** [github.com/dezsirazvan/ez_logs_agent_nextjs/issues](https://github.com/dezsirazvan/ez_logs_agent_nextjs/issues)
777
+ - **Email:** support@ezlogs.io
778
+
779
+ **Made for everyone on your team, not just engineers.**