@logbrew/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 CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  Next.js App Router helpers for the public LogBrew JavaScript SDK.
8
8
 
9
- This package is intentionally thin. It creates server-side LogBrew clients, wraps App Router Route Handlers, captures successful route requests and thrown route errors, and still keeps manual event creation available through the route helpers.
9
+ This package is intentionally thin. It creates server-side LogBrew clients, observes App Router request errors through Next.js instrumentation, wraps Route Handlers, captures successful route requests and thrown route errors, and still keeps manual event creation available through the route helpers.
10
10
 
11
11
  ## Install
12
12
 
@@ -103,6 +103,44 @@ export default withLogBrewNextReleaseArtifacts(
103
103
 
104
104
  The helper defaults minified URLs to `app:///_next/static/chunks/...`. Use `minifiedPathPrefix`, `manifestPath`, `repositoryUrl`, `commitSha`, or `stripSourcePrefix` when your deploy needs explicit paths or source-link metadata. Set `LOGBREW_RELEASE_ARTIFACT_TOKEN` in the build environment to a dedicated release-artifact token. Use `tokenEnv` for a different CI variable, or `dryRun: true` to prepare the complete build output without a network request. Existing `compiler.runAfterProductionCompile` work runs first. Upload is disabled when `upload` is omitted, and any unsafe preparation or upload result fails the production build without exposing response text or secret values.
105
105
 
106
+ ## App Router Request Errors
107
+
108
+ Use Next.js's root `instrumentation.ts` file when you want one server error hook
109
+ for React Server Components, Route Handlers, Server Actions, and Proxy. The
110
+ instrumentation subpath stays safe to import in mixed-runtime applications and
111
+ delivers only from the Node.js runtime:
112
+
113
+ ```ts
114
+ // instrumentation.ts
115
+ import { createLogBrewNextRequestErrorHandler } from "@logbrew/next/instrumentation";
116
+
117
+ export const onRequestError = createLogBrewNextRequestErrorHandler({
118
+ serverApiKey: process.env.LOGBREW_SERVER_API_KEY,
119
+ onCaptureError(error) {
120
+ console.error("LogBrew request-error capture failed", error);
121
+ }
122
+ });
123
+ ```
124
+
125
+ Next.js awaits `onRequestError`, and the LogBrew adapter awaits delivery before
126
+ it returns. A delivery or callback failure is reported through
127
+ `onCaptureError` but never replaces the application error that Next.js is
128
+ already handling. The Edge runtime is left unchanged; use a Node.js route or
129
+ server boundary for LogBrew server delivery.
130
+
131
+ By default, the issue includes the error message, Next.js error digest, method,
132
+ stable route file path, router kind, route type, render source, revalidation
133
+ reason, and render type when Next.js supplies them. It does not capture request
134
+ headers, authorization values, cookies, request bodies, query strings, URL
135
+ fragments, concrete dynamic path values, or raw stack text. Set
136
+ `includePathname: true` only when a query-free concrete pathname is intentional
137
+ and acceptable for that application.
138
+
139
+ If the same Route Handler also uses `withLogBrewRouteHandler`, set
140
+ `captureErrors: false` on that wrapper so the global request-error hook is the
141
+ single issue owner. The wrapper can continue to capture successful requests,
142
+ metrics, and trace context.
143
+
106
144
  ## App Router Route Handler
107
145
 
108
146
  ```js
@@ -194,7 +232,7 @@ import {
194
232
  const client = createLogBrewNextBrowserClient({
195
233
  clientKey: "LOGBREW_CLIENT_KEY",
196
234
  sdkName: "my-next-app",
197
- sdkVersion: "0.1.2"
235
+ sdkVersion: "0.1.3"
198
236
  });
199
237
 
200
238
  const routePatterns = [
@@ -231,10 +269,15 @@ import { createLogBrewNextClient } from "@logbrew/next";
231
269
  const client = createLogBrewNextClient({
232
270
  serverApiKey: "LOGBREW_SERVER_API_KEY",
233
271
  sdkName: "my-next-app",
234
- sdkVersion: "0.1.2"
272
+ sdkVersion: "0.1.3"
235
273
  });
236
274
  ```
237
275
 
238
276
  ## Example Source
239
277
 
240
- The package includes example source for App Router Route Handlers, server-side client creation, and app-owned responses. The packaged server examples use an explicit `RecordingTransport` so they can run offline and print serialized event batches without sending them. Use the default network-delivery snippets above as the starting point for wiring LogBrew into your Next.js application.
278
+ The package includes example source for App Router request-error instrumentation, Route Handlers, server-side client creation, and app-owned responses. The packaged server examples use an explicit `RecordingTransport` so they can run offline and print serialized event batches without sending them. Use the default network-delivery snippets above as the starting point for wiring LogBrew into your Next.js application.
279
+
280
+ ```bash
281
+ node node_modules/@logbrew/next/examples/index.mjs request-errors
282
+ npm --prefix node_modules/@logbrew/next/examples run request-errors
283
+ ```
package/client.cjs CHANGED
@@ -8,7 +8,7 @@ const {
8
8
  } = require("@logbrew/sdk");
9
9
 
10
10
  const DEFAULT_SDK_NAME = "logbrew-next-client";
11
- const DEFAULT_SDK_VERSION = "0.1.2";
11
+ const DEFAULT_SDK_VERSION = "0.1.3";
12
12
 
13
13
  function createLogBrewNextBrowserClient({
14
14
  apiKey,
package/client.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  } from "@logbrew/sdk";
9
9
 
10
10
  const DEFAULT_SDK_NAME = "logbrew-next-client";
11
- const DEFAULT_SDK_VERSION = "0.1.2";
11
+ const DEFAULT_SDK_VERSION = "0.1.3";
12
12
 
13
13
  export function createLogBrewNextBrowserClient({
14
14
  apiKey,
@@ -13,7 +13,7 @@ const routeTemplate = createNextRouteTemplate({
13
13
  const client = createLogBrewNextBrowserClient({
14
14
  clientKey: "LOGBREW_CLIENT_KEY",
15
15
  sdkName: "logbrew-next-client-route-example",
16
- sdkVersion: "0.1.2"
16
+ sdkVersion: "0.1.3"
17
17
  });
18
18
 
19
19
  const event = captureNextNavigation(client, {
@@ -3,6 +3,7 @@
3
3
  const commands = new Map([
4
4
  ["client-route-spans", new URL("./client-route-spans.mjs", import.meta.url)],
5
5
  ["readme-example", new URL("./readme-example.mjs", import.meta.url)],
6
+ ["request-errors", new URL("./request-errors.mjs", import.meta.url)],
6
7
  ["real-user-smoke", new URL("./real-user-smoke.mjs", import.meta.url)]
7
8
  ]);
8
9
 
@@ -25,16 +26,19 @@ function printHelp() {
25
26
  console.log("node node_modules/@logbrew/next/examples/index.mjs --list");
26
27
  console.log("node node_modules/@logbrew/next/examples/index.mjs client-route-spans");
27
28
  console.log("node node_modules/@logbrew/next/examples/index.mjs readme-example");
29
+ console.log("node node_modules/@logbrew/next/examples/index.mjs request-errors");
28
30
  console.log("node node_modules/@logbrew/next/examples/index.mjs real-user-smoke");
29
31
  console.log("node node_modules/@logbrew/next/examples/index.mjs");
30
32
  console.log("npm --prefix node_modules/@logbrew/next/examples run list");
31
33
  console.log("npm --prefix node_modules/@logbrew/next/examples run client-route-spans");
32
34
  console.log("npm --prefix node_modules/@logbrew/next/examples run readme-example");
35
+ console.log("npm --prefix node_modules/@logbrew/next/examples run request-errors");
33
36
  console.log("npm --prefix node_modules/@logbrew/next/examples run real-user-smoke");
34
37
  }
35
38
 
36
39
  function printList() {
37
40
  console.log("client-route-spans -> node node_modules/@logbrew/next/examples/index.mjs client-route-spans");
38
41
  console.log("readme-example -> node node_modules/@logbrew/next/examples/index.mjs readme-example");
42
+ console.log("request-errors -> node node_modules/@logbrew/next/examples/index.mjs request-errors");
39
43
  console.log("real-user-smoke -> node node_modules/@logbrew/next/examples/index.mjs real-user-smoke");
40
44
  }
@@ -6,6 +6,7 @@
6
6
  "help": "node ./index.mjs --help",
7
7
  "list": "node ./index.mjs --list",
8
8
  "readme-example": "node ./index.mjs readme-example",
9
+ "request-errors": "node ./index.mjs request-errors",
9
10
  "real-user-smoke": "node ./index.mjs real-user-smoke"
10
11
  }
11
12
  }
@@ -12,7 +12,7 @@ const POST = withLogBrewRouteHandler(
12
12
  serverApiKey: "LOGBREW_SERVER_API_KEY",
13
13
  captureRequests: false,
14
14
  sdkName: "logbrew-next-readme-example",
15
- sdkVersion: "0.1.2",
15
+ sdkVersion: "0.1.3",
16
16
  transport
17
17
  }
18
18
  );
@@ -12,7 +12,7 @@ const POST = withLogBrewRouteHandler(
12
12
  serverApiKey: "LOGBREW_SERVER_API_KEY",
13
13
  captureRequests: false,
14
14
  sdkName: "logbrew-next-real-user-smoke",
15
- sdkVersion: "0.1.2",
15
+ sdkVersion: "0.1.3",
16
16
  maxRetries: 1,
17
17
  transport
18
18
  }
@@ -0,0 +1,32 @@
1
+ import { RecordingTransport } from "@logbrew/sdk";
2
+ import { createLogBrewNextRequestErrorHandler } from "@logbrew/next/instrumentation";
3
+
4
+ const transport = RecordingTransport.alwaysAccept();
5
+ const onRequestError = createLogBrewNextRequestErrorHandler({
6
+ serverApiKey: "LOGBREW_SERVER_API_KEY",
7
+ transport,
8
+ idFactory: () => "evt_next_request_error_example",
9
+ now: () => "2026-08-01T10:00:00Z"
10
+ });
11
+
12
+ const error = Object.assign(new Error("checkout render failed"), {
13
+ digest: "next_digest_example"
14
+ });
15
+ await onRequestError(
16
+ error,
17
+ {
18
+ path: "/orders/example?debug=sample",
19
+ method: "POST",
20
+ headers: {}
21
+ },
22
+ {
23
+ routerKind: "App Router",
24
+ routePath: "/app/orders/[orderId]/page",
25
+ routeType: "render",
26
+ renderSource: "react-server-components",
27
+ renderType: "dynamic"
28
+ }
29
+ );
30
+
31
+ console.log(transport.lastBody());
32
+ console.error(JSON.stringify({ ok: true, attempts: transport.sentBodies.length }));
package/index.cjs CHANGED
@@ -7,7 +7,18 @@ const {
7
7
  const { createNodeFetchTransport } = require("@logbrew/node");
8
8
 
9
9
  const DEFAULT_SDK_NAME = "logbrew-next";
10
- const DEFAULT_SDK_VERSION = "0.1.2";
10
+ const DEFAULT_SDK_VERSION = "0.1.3";
11
+ const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
12
+ const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
13
+ const NEXT_RENDER_SOURCES = new Set([
14
+ "react-server-components",
15
+ "react-server-components-payload",
16
+ "server-rendering"
17
+ ]);
18
+ const NEXT_RENDER_TYPES = new Set(["dynamic", "dynamic-resume"]);
19
+ const NEXT_REVALIDATE_REASONS = new Set(["on-demand", "stale"]);
20
+ const NEXT_ROUTE_TYPES = new Set(["action", "middleware", "proxy", "render", "route"]);
21
+ const NEXT_ROUTER_KINDS = new Set(["App Router", "Pages Router"]);
11
22
  const activeTraceContext = new AsyncLocalStorage();
12
23
 
13
24
  function createLogBrewNextClient({
@@ -27,6 +38,69 @@ function createLogBrewNextClient({
27
38
  return LogBrewClient.create({ apiKey: authKey, sdkName, sdkVersion, maxRetries });
28
39
  }
29
40
 
41
+ function createLogBrewNextRequestErrorHandler(options = {}) {
42
+ const defaultTransport = options.transport === undefined
43
+ ? createNodeFetchTransport(options)
44
+ : undefined;
45
+
46
+ return async function logBrewNextRequestErrorHandler(error, request = {}, context = {}) {
47
+ let runtime = { error, request, context };
48
+ try {
49
+ const resolvedClient = resolveRequestErrorClient(options, runtime);
50
+ const client = resolvedClient.client;
51
+ const transport = resolveRequestErrorTransport(options, { ...runtime, client }, defaultTransport);
52
+ runtime = { ...runtime, client, transport };
53
+ const event = typeof options.errorEvent === "function"
54
+ ? options.errorEvent(error, runtime)
55
+ : createNextRequestErrorEvent(error, request, context, options);
56
+
57
+ client.issue(event.id, event.timestamp, event.attributes);
58
+ const response = resolvedClient.owned
59
+ ? await client.shutdown(transport)
60
+ : await client.flush(transport);
61
+ await notifyFlush(options, response, runtime);
62
+ } catch (captureError) {
63
+ try {
64
+ await notifyFailure(options, captureError, runtime);
65
+ } catch {
66
+ // Observability callbacks must not replace the application error Next.js is handling.
67
+ }
68
+ }
69
+ };
70
+ }
71
+
72
+ function createNextRequestErrorEvent(error, request = {}, context = {}, {
73
+ includePathname = false,
74
+ now = () => new Date().toISOString(),
75
+ idFactory = defaultNextRequestErrorId
76
+ } = {}) {
77
+ const method = nextRequestMethod(request);
78
+ const routePath = nextRoutePath(context?.routePath);
79
+ const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
80
+ const errorDigest = nextErrorDigest(error);
81
+ return {
82
+ id: idFactory(error, request, context),
83
+ timestamp: now(),
84
+ attributes: {
85
+ title: `${method} ${routePath} failed`,
86
+ level: "error",
87
+ message: nextErrorMessage(error),
88
+ metadata: {
89
+ framework: "nextjs",
90
+ method,
91
+ routePath,
92
+ ...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
93
+ ...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
94
+ ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
95
+ ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
96
+ ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
97
+ ...(errorDigest ? { errorDigest } : {}),
98
+ ...(pathname ? { pathname } : {})
99
+ }
100
+ }
101
+ };
102
+ }
103
+
30
104
  function withLogBrewRouteHandler(handler, options = {}) {
31
105
  if (typeof handler !== "function") {
32
106
  throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
@@ -179,6 +253,23 @@ function resolveTransport(options, request, context, client, defaultTransport) {
179
253
  return options.transport ?? defaultTransport;
180
254
  }
181
255
 
256
+ function resolveRequestErrorClient(options, runtime) {
257
+ if (typeof options.client === "function") {
258
+ return { client: options.client(runtime), owned: true };
259
+ }
260
+ if (options.client) {
261
+ return { client: options.client, owned: false };
262
+ }
263
+ return { client: createLogBrewNextClient(options), owned: true };
264
+ }
265
+
266
+ function resolveRequestErrorTransport(options, runtime, defaultTransport) {
267
+ if (typeof options.transport === "function") {
268
+ return options.transport(runtime);
269
+ }
270
+ return options.transport ?? defaultTransport;
271
+ }
272
+
182
273
  function createRouteHelpers(client, transport, trace) {
183
274
  return {
184
275
  client,
@@ -302,6 +393,10 @@ function defaultRouteErrorId(request) {
302
393
  return `evt_next_error_${slug || "route"}`;
303
394
  }
304
395
 
396
+ function defaultNextRequestErrorId() {
397
+ return `evt_next_request_error_${randomHex(8)}`;
398
+ }
399
+
305
400
  function defaultRouteMetricId(request, response, routeTemplate = safeUrl(request).pathname) {
306
401
  const sanitizedRouteTemplate = routeTemplateOnly(routeTemplate);
307
402
  const slug = `${request?.method ?? "GET"}-${sanitizedRouteTemplate}-${response?.status ?? 0}`
@@ -319,6 +414,55 @@ function safeUrl(request) {
319
414
  }
320
415
  }
321
416
 
417
+ function nextRequestMethod(request) {
418
+ const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
419
+ return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
420
+ }
421
+
422
+ function nextRoutePath(value) {
423
+ if (typeof value !== "string" || value.trim() === "") {
424
+ return "/";
425
+ }
426
+ let pathname;
427
+ try {
428
+ pathname = new URL(value, "http://localhost").pathname;
429
+ } catch {
430
+ pathname = value.split(/[?#]/u)[0];
431
+ }
432
+ if (typeof pathname !== "string" || pathname === "") {
433
+ return "/";
434
+ }
435
+ const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
436
+ return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
437
+ }
438
+
439
+ function nextCategoricalMetadata(key, value, allowed) {
440
+ return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
441
+ }
442
+
443
+ function nextErrorDigest(error) {
444
+ const digest = error && typeof error === "object" ? error.digest : undefined;
445
+ if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
446
+ return undefined;
447
+ }
448
+ return digest;
449
+ }
450
+
451
+ function nextErrorMessage(error) {
452
+ let message;
453
+ try {
454
+ message = error instanceof Error ? error.message : String(error);
455
+ } catch {
456
+ message = "Next.js request failed";
457
+ }
458
+ const normalized = typeof message === "string" && message.trim() !== ""
459
+ ? message
460
+ : "Next.js request failed";
461
+ return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
462
+ ? normalized
463
+ : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
464
+ }
465
+
322
466
  function getTraceparentHeader(request) {
323
467
  if (!request?.headers || typeof request.headers.get !== "function") {
324
468
  return undefined;
@@ -468,6 +612,8 @@ function readEnvServerApiKey() {
468
612
 
469
613
  module.exports = {
470
614
  createLogBrewNextClient,
615
+ createLogBrewNextRequestErrorHandler,
616
+ createNextRequestErrorEvent,
471
617
  createRequestMetricEvent,
472
618
  createRouteErrorEvent,
473
619
  createRouteRequestEvent,
package/index.d.cts CHANGED
@@ -22,6 +22,77 @@ export type CreateLogBrewNextClientConfig = {
22
22
  maxRetries?: number;
23
23
  };
24
24
 
25
+ export type LogBrewNextRequestError = unknown;
26
+
27
+ export type LogBrewNextRequestErrorRequest = Readonly<{
28
+ path: string;
29
+ method: string;
30
+ headers: Readonly<Record<string, string | string[] | undefined>>;
31
+ }>;
32
+
33
+ export type LogBrewNextRequestErrorContext = Readonly<{
34
+ routerKind: "App Router" | "Pages Router";
35
+ routePath: string;
36
+ routeType: "action" | "middleware" | "proxy" | "render" | "route";
37
+ renderSource?: "react-server-components" | "react-server-components-payload" | "server-rendering";
38
+ revalidateReason?: "on-demand" | "stale";
39
+ renderType?: "dynamic" | "dynamic-resume";
40
+ }>;
41
+
42
+ export type LogBrewNextRequestErrorInput = {
43
+ error: LogBrewNextRequestError;
44
+ request: LogBrewNextRequestErrorRequest;
45
+ context: LogBrewNextRequestErrorContext;
46
+ };
47
+
48
+ export type LogBrewNextRequestErrorRuntimeContext = LogBrewNextRequestErrorInput & {
49
+ client?: LogBrewClient;
50
+ transport?: Transport;
51
+ };
52
+
53
+ export type LogBrewNextRequestErrorCaptureContext = LogBrewNextRequestErrorInput & {
54
+ client: LogBrewClient;
55
+ transport: Transport;
56
+ };
57
+
58
+ export type LogBrewNextRequestErrorEvent = {
59
+ id: string;
60
+ timestamp: string;
61
+ attributes: IssueAttributes;
62
+ };
63
+
64
+ export type LogBrewNextRequestErrorHandler = (
65
+ error: LogBrewNextRequestError,
66
+ request: LogBrewNextRequestErrorRequest,
67
+ context: LogBrewNextRequestErrorContext
68
+ ) => Promise<void>;
69
+
70
+ export type LogBrewNextRequestErrorOptions = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
71
+ /** A fixed client stays caller-owned and is flushed, not shut down. A factory must return a fresh client per error. */
72
+ client?: LogBrewClient | ((input: LogBrewNextRequestErrorInput) => LogBrewClient);
73
+ transport?: Transport | ((context: LogBrewNextRequestErrorInput & { client: LogBrewClient }) => Transport);
74
+ /** Opt into a query-free concrete pathname. Stable routePath metadata remains the default. */
75
+ includePathname?: boolean;
76
+ now?: () => string;
77
+ idFactory?: (
78
+ error: LogBrewNextRequestError,
79
+ request: LogBrewNextRequestErrorRequest,
80
+ context: LogBrewNextRequestErrorContext
81
+ ) => string;
82
+ errorEvent?: (
83
+ error: LogBrewNextRequestError,
84
+ context: LogBrewNextRequestErrorCaptureContext
85
+ ) => LogBrewNextRequestErrorEvent;
86
+ onFlush?: (
87
+ response: TransportResponse,
88
+ context: LogBrewNextRequestErrorCaptureContext
89
+ ) => void | Promise<void>;
90
+ onCaptureError?: (
91
+ error: unknown,
92
+ context: LogBrewNextRequestErrorRuntimeContext
93
+ ) => void | Promise<void>;
94
+ };
95
+
25
96
  export type LogBrewRouteContext = Record<string, unknown>;
26
97
 
27
98
  export type LogBrewTraceContext = {
@@ -140,6 +211,25 @@ export declare function createLogBrewNextClient(
140
211
  config?: CreateLogBrewNextClientConfig
141
212
  ): LogBrewClient;
142
213
 
214
+ export declare function createLogBrewNextRequestErrorHandler(
215
+ options?: LogBrewNextRequestErrorOptions
216
+ ): LogBrewNextRequestErrorHandler;
217
+
218
+ export declare function createNextRequestErrorEvent(
219
+ error: LogBrewNextRequestError,
220
+ request: LogBrewNextRequestErrorRequest,
221
+ context: LogBrewNextRequestErrorContext,
222
+ options?: {
223
+ includePathname?: boolean;
224
+ now?: () => string;
225
+ idFactory?: (
226
+ error: LogBrewNextRequestError,
227
+ request: LogBrewNextRequestErrorRequest,
228
+ context: LogBrewNextRequestErrorContext
229
+ ) => string;
230
+ }
231
+ ): LogBrewNextRequestErrorEvent;
232
+
143
233
  export declare function withLogBrewRouteHandler<TContext = LogBrewRouteContext>(
144
234
  handler: LogBrewRouteHandler<TContext>,
145
235
  options?: LogBrewRouteOptions<TContext>
@@ -184,6 +274,8 @@ export declare function createRouteErrorEvent(
184
274
 
185
275
  declare const defaultExport: {
186
276
  createLogBrewNextClient: typeof createLogBrewNextClient;
277
+ createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
278
+ createNextRequestErrorEvent: typeof createNextRequestErrorEvent;
187
279
  createRequestMetricEvent: typeof createRequestMetricEvent;
188
280
  createRouteErrorEvent: typeof createRouteErrorEvent;
189
281
  createRouteRequestEvent: typeof createRouteRequestEvent;
package/index.d.ts CHANGED
@@ -22,6 +22,77 @@ export type CreateLogBrewNextClientConfig = {
22
22
  maxRetries?: number;
23
23
  };
24
24
 
25
+ export type LogBrewNextRequestError = unknown;
26
+
27
+ export type LogBrewNextRequestErrorRequest = Readonly<{
28
+ path: string;
29
+ method: string;
30
+ headers: Readonly<Record<string, string | string[] | undefined>>;
31
+ }>;
32
+
33
+ export type LogBrewNextRequestErrorContext = Readonly<{
34
+ routerKind: "App Router" | "Pages Router";
35
+ routePath: string;
36
+ routeType: "action" | "middleware" | "proxy" | "render" | "route";
37
+ renderSource?: "react-server-components" | "react-server-components-payload" | "server-rendering";
38
+ revalidateReason?: "on-demand" | "stale";
39
+ renderType?: "dynamic" | "dynamic-resume";
40
+ }>;
41
+
42
+ export type LogBrewNextRequestErrorInput = {
43
+ error: LogBrewNextRequestError;
44
+ request: LogBrewNextRequestErrorRequest;
45
+ context: LogBrewNextRequestErrorContext;
46
+ };
47
+
48
+ export type LogBrewNextRequestErrorRuntimeContext = LogBrewNextRequestErrorInput & {
49
+ client?: LogBrewClient;
50
+ transport?: Transport;
51
+ };
52
+
53
+ export type LogBrewNextRequestErrorCaptureContext = LogBrewNextRequestErrorInput & {
54
+ client: LogBrewClient;
55
+ transport: Transport;
56
+ };
57
+
58
+ export type LogBrewNextRequestErrorEvent = {
59
+ id: string;
60
+ timestamp: string;
61
+ attributes: IssueAttributes;
62
+ };
63
+
64
+ export type LogBrewNextRequestErrorHandler = (
65
+ error: LogBrewNextRequestError,
66
+ request: LogBrewNextRequestErrorRequest,
67
+ context: LogBrewNextRequestErrorContext
68
+ ) => Promise<void>;
69
+
70
+ export type LogBrewNextRequestErrorOptions = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
71
+ /** A fixed client stays caller-owned and is flushed, not shut down. A factory must return a fresh client per error. */
72
+ client?: LogBrewClient | ((input: LogBrewNextRequestErrorInput) => LogBrewClient);
73
+ transport?: Transport | ((context: LogBrewNextRequestErrorInput & { client: LogBrewClient }) => Transport);
74
+ /** Opt into a query-free concrete pathname. Stable routePath metadata remains the default. */
75
+ includePathname?: boolean;
76
+ now?: () => string;
77
+ idFactory?: (
78
+ error: LogBrewNextRequestError,
79
+ request: LogBrewNextRequestErrorRequest,
80
+ context: LogBrewNextRequestErrorContext
81
+ ) => string;
82
+ errorEvent?: (
83
+ error: LogBrewNextRequestError,
84
+ context: LogBrewNextRequestErrorCaptureContext
85
+ ) => LogBrewNextRequestErrorEvent;
86
+ onFlush?: (
87
+ response: TransportResponse,
88
+ context: LogBrewNextRequestErrorCaptureContext
89
+ ) => void | Promise<void>;
90
+ onCaptureError?: (
91
+ error: unknown,
92
+ context: LogBrewNextRequestErrorRuntimeContext
93
+ ) => void | Promise<void>;
94
+ };
95
+
25
96
  export type LogBrewRouteContext = Record<string, unknown>;
26
97
 
27
98
  export type LogBrewTraceContext = {
@@ -140,6 +211,25 @@ export declare function createLogBrewNextClient(
140
211
  config?: CreateLogBrewNextClientConfig
141
212
  ): LogBrewClient;
142
213
 
214
+ export declare function createLogBrewNextRequestErrorHandler(
215
+ options?: LogBrewNextRequestErrorOptions
216
+ ): LogBrewNextRequestErrorHandler;
217
+
218
+ export declare function createNextRequestErrorEvent(
219
+ error: LogBrewNextRequestError,
220
+ request: LogBrewNextRequestErrorRequest,
221
+ context: LogBrewNextRequestErrorContext,
222
+ options?: {
223
+ includePathname?: boolean;
224
+ now?: () => string;
225
+ idFactory?: (
226
+ error: LogBrewNextRequestError,
227
+ request: LogBrewNextRequestErrorRequest,
228
+ context: LogBrewNextRequestErrorContext
229
+ ) => string;
230
+ }
231
+ ): LogBrewNextRequestErrorEvent;
232
+
143
233
  export declare function withLogBrewRouteHandler<TContext = LogBrewRouteContext>(
144
234
  handler: LogBrewRouteHandler<TContext>,
145
235
  options?: LogBrewRouteOptions<TContext>
@@ -184,6 +274,8 @@ export declare function createRouteErrorEvent(
184
274
 
185
275
  declare const defaultExport: {
186
276
  createLogBrewNextClient: typeof createLogBrewNextClient;
277
+ createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
278
+ createNextRequestErrorEvent: typeof createNextRequestErrorEvent;
187
279
  createRequestMetricEvent: typeof createRequestMetricEvent;
188
280
  createRouteErrorEvent: typeof createRouteErrorEvent;
189
281
  createRouteRequestEvent: typeof createRouteRequestEvent;
package/index.js CHANGED
@@ -7,7 +7,18 @@ import {
7
7
  import { createNodeFetchTransport } from "@logbrew/node";
8
8
 
9
9
  const DEFAULT_SDK_NAME = "logbrew-next";
10
- const DEFAULT_SDK_VERSION = "0.1.2";
10
+ const DEFAULT_SDK_VERSION = "0.1.3";
11
+ const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
12
+ const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
13
+ const NEXT_RENDER_SOURCES = new Set([
14
+ "react-server-components",
15
+ "react-server-components-payload",
16
+ "server-rendering"
17
+ ]);
18
+ const NEXT_RENDER_TYPES = new Set(["dynamic", "dynamic-resume"]);
19
+ const NEXT_REVALIDATE_REASONS = new Set(["on-demand", "stale"]);
20
+ const NEXT_ROUTE_TYPES = new Set(["action", "middleware", "proxy", "render", "route"]);
21
+ const NEXT_ROUTER_KINDS = new Set(["App Router", "Pages Router"]);
11
22
  const activeTraceContext = new AsyncLocalStorage();
12
23
 
13
24
  export function createLogBrewNextClient({
@@ -27,6 +38,69 @@ export function createLogBrewNextClient({
27
38
  return LogBrewClient.create({ apiKey: authKey, sdkName, sdkVersion, maxRetries });
28
39
  }
29
40
 
41
+ export function createLogBrewNextRequestErrorHandler(options = {}) {
42
+ const defaultTransport = options.transport === undefined
43
+ ? createNodeFetchTransport(options)
44
+ : undefined;
45
+
46
+ return async function logBrewNextRequestErrorHandler(error, request = {}, context = {}) {
47
+ let runtime = { error, request, context };
48
+ try {
49
+ const resolvedClient = resolveRequestErrorClient(options, runtime);
50
+ const client = resolvedClient.client;
51
+ const transport = resolveRequestErrorTransport(options, { ...runtime, client }, defaultTransport);
52
+ runtime = { ...runtime, client, transport };
53
+ const event = typeof options.errorEvent === "function"
54
+ ? options.errorEvent(error, runtime)
55
+ : createNextRequestErrorEvent(error, request, context, options);
56
+
57
+ client.issue(event.id, event.timestamp, event.attributes);
58
+ const response = resolvedClient.owned
59
+ ? await client.shutdown(transport)
60
+ : await client.flush(transport);
61
+ await notifyFlush(options, response, runtime);
62
+ } catch (captureError) {
63
+ try {
64
+ await notifyFailure(options, captureError, runtime);
65
+ } catch {
66
+ // Observability callbacks must not replace the application error Next.js is handling.
67
+ }
68
+ }
69
+ };
70
+ }
71
+
72
+ export function createNextRequestErrorEvent(error, request = {}, context = {}, {
73
+ includePathname = false,
74
+ now = () => new Date().toISOString(),
75
+ idFactory = defaultNextRequestErrorId
76
+ } = {}) {
77
+ const method = nextRequestMethod(request);
78
+ const routePath = nextRoutePath(context?.routePath);
79
+ const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
80
+ const errorDigest = nextErrorDigest(error);
81
+ return {
82
+ id: idFactory(error, request, context),
83
+ timestamp: now(),
84
+ attributes: {
85
+ title: `${method} ${routePath} failed`,
86
+ level: "error",
87
+ message: nextErrorMessage(error),
88
+ metadata: {
89
+ framework: "nextjs",
90
+ method,
91
+ routePath,
92
+ ...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
93
+ ...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
94
+ ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
95
+ ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
96
+ ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
97
+ ...(errorDigest ? { errorDigest } : {}),
98
+ ...(pathname ? { pathname } : {})
99
+ }
100
+ }
101
+ };
102
+ }
103
+
30
104
  export function withLogBrewRouteHandler(handler, options = {}) {
31
105
  if (typeof handler !== "function") {
32
106
  throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
@@ -179,6 +253,23 @@ function resolveTransport(options, request, context, client, defaultTransport) {
179
253
  return options.transport ?? defaultTransport;
180
254
  }
181
255
 
256
+ function resolveRequestErrorClient(options, runtime) {
257
+ if (typeof options.client === "function") {
258
+ return { client: options.client(runtime), owned: true };
259
+ }
260
+ if (options.client) {
261
+ return { client: options.client, owned: false };
262
+ }
263
+ return { client: createLogBrewNextClient(options), owned: true };
264
+ }
265
+
266
+ function resolveRequestErrorTransport(options, runtime, defaultTransport) {
267
+ if (typeof options.transport === "function") {
268
+ return options.transport(runtime);
269
+ }
270
+ return options.transport ?? defaultTransport;
271
+ }
272
+
182
273
  function createRouteHelpers(client, transport, trace) {
183
274
  return {
184
275
  client,
@@ -302,6 +393,10 @@ function defaultRouteErrorId(request) {
302
393
  return `evt_next_error_${slug || "route"}`;
303
394
  }
304
395
 
396
+ function defaultNextRequestErrorId() {
397
+ return `evt_next_request_error_${randomHex(8)}`;
398
+ }
399
+
305
400
  function defaultRouteMetricId(request, response, routeTemplate = safeUrl(request).pathname) {
306
401
  const sanitizedRouteTemplate = routeTemplateOnly(routeTemplate);
307
402
  const slug = `${request?.method ?? "GET"}-${sanitizedRouteTemplate}-${response?.status ?? 0}`
@@ -319,6 +414,55 @@ function safeUrl(request) {
319
414
  }
320
415
  }
321
416
 
417
+ function nextRequestMethod(request) {
418
+ const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
419
+ return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
420
+ }
421
+
422
+ function nextRoutePath(value) {
423
+ if (typeof value !== "string" || value.trim() === "") {
424
+ return "/";
425
+ }
426
+ let pathname;
427
+ try {
428
+ pathname = new URL(value, "http://localhost").pathname;
429
+ } catch {
430
+ pathname = value.split(/[?#]/u)[0];
431
+ }
432
+ if (typeof pathname !== "string" || pathname === "") {
433
+ return "/";
434
+ }
435
+ const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
436
+ return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
437
+ }
438
+
439
+ function nextCategoricalMetadata(key, value, allowed) {
440
+ return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
441
+ }
442
+
443
+ function nextErrorDigest(error) {
444
+ const digest = error && typeof error === "object" ? error.digest : undefined;
445
+ if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
446
+ return undefined;
447
+ }
448
+ return digest;
449
+ }
450
+
451
+ function nextErrorMessage(error) {
452
+ let message;
453
+ try {
454
+ message = error instanceof Error ? error.message : String(error);
455
+ } catch {
456
+ message = "Next.js request failed";
457
+ }
458
+ const normalized = typeof message === "string" && message.trim() !== ""
459
+ ? message
460
+ : "Next.js request failed";
461
+ return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
462
+ ? normalized
463
+ : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
464
+ }
465
+
322
466
  function getTraceparentHeader(request) {
323
467
  if (!request?.headers || typeof request.headers.get !== "function") {
324
468
  return undefined;
@@ -468,6 +612,8 @@ function readEnvServerApiKey() {
468
612
 
469
613
  export default {
470
614
  createLogBrewNextClient,
615
+ createLogBrewNextRequestErrorHandler,
616
+ createNextRequestErrorEvent,
471
617
  createRequestMetricEvent,
472
618
  createRouteErrorEvent,
473
619
  createRouteRequestEvent,
@@ -0,0 +1,29 @@
1
+ let nodeHandlerPromise;
2
+
3
+ function createLogBrewNextRequestErrorHandler(options = {}) {
4
+ let handler;
5
+ return async function logBrewNextRequestErrorHandler(error, request, context) {
6
+ if (globalThis.process?.env?.NEXT_RUNTIME === "edge") {
7
+ return;
8
+ }
9
+
10
+ try {
11
+ nodeHandlerPromise ??= Promise.resolve().then(() => require("./index.cjs"));
12
+ const module = await nodeHandlerPromise;
13
+ handler ??= module.createLogBrewNextRequestErrorHandler(options);
14
+ await handler(error, request, context);
15
+ } catch (captureError) {
16
+ if (typeof options.onCaptureError === "function") {
17
+ try {
18
+ await options.onCaptureError(captureError, { error, request, context });
19
+ } catch {
20
+ // Observability callbacks must not replace the application error Next.js is handling.
21
+ }
22
+ }
23
+ }
24
+ };
25
+ }
26
+
27
+ module.exports = {
28
+ createLogBrewNextRequestErrorHandler
29
+ };
@@ -0,0 +1,26 @@
1
+ import type {
2
+ LogBrewNextRequestErrorHandler,
3
+ LogBrewNextRequestErrorOptions
4
+ } from "./index.cjs";
5
+
6
+ export type {
7
+ LogBrewNextRequestError,
8
+ LogBrewNextRequestErrorCaptureContext,
9
+ LogBrewNextRequestErrorContext,
10
+ LogBrewNextRequestErrorEvent,
11
+ LogBrewNextRequestErrorHandler,
12
+ LogBrewNextRequestErrorInput,
13
+ LogBrewNextRequestErrorOptions,
14
+ LogBrewNextRequestErrorRequest,
15
+ LogBrewNextRequestErrorRuntimeContext
16
+ } from "./index.cjs";
17
+
18
+ export declare function createLogBrewNextRequestErrorHandler(
19
+ options?: LogBrewNextRequestErrorOptions
20
+ ): LogBrewNextRequestErrorHandler;
21
+
22
+ declare const defaultExport: {
23
+ createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
24
+ };
25
+
26
+ export default defaultExport;
@@ -0,0 +1,26 @@
1
+ import type {
2
+ LogBrewNextRequestErrorHandler,
3
+ LogBrewNextRequestErrorOptions
4
+ } from "./index.js";
5
+
6
+ export type {
7
+ LogBrewNextRequestError,
8
+ LogBrewNextRequestErrorCaptureContext,
9
+ LogBrewNextRequestErrorContext,
10
+ LogBrewNextRequestErrorEvent,
11
+ LogBrewNextRequestErrorHandler,
12
+ LogBrewNextRequestErrorInput,
13
+ LogBrewNextRequestErrorOptions,
14
+ LogBrewNextRequestErrorRequest,
15
+ LogBrewNextRequestErrorRuntimeContext
16
+ } from "./index.js";
17
+
18
+ export declare function createLogBrewNextRequestErrorHandler(
19
+ options?: LogBrewNextRequestErrorOptions
20
+ ): LogBrewNextRequestErrorHandler;
21
+
22
+ declare const defaultExport: {
23
+ createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
24
+ };
25
+
26
+ export default defaultExport;
@@ -0,0 +1,29 @@
1
+ let nodeHandlerPromise;
2
+
3
+ export function createLogBrewNextRequestErrorHandler(options = {}) {
4
+ let handler;
5
+ return async function logBrewNextRequestErrorHandler(error, request, context) {
6
+ if (globalThis.process?.env?.NEXT_RUNTIME === "edge") {
7
+ return;
8
+ }
9
+
10
+ try {
11
+ nodeHandlerPromise ??= import("./index.js");
12
+ const module = await nodeHandlerPromise;
13
+ handler ??= module.createLogBrewNextRequestErrorHandler(options);
14
+ await handler(error, request, context);
15
+ } catch (captureError) {
16
+ if (typeof options.onCaptureError === "function") {
17
+ try {
18
+ await options.onCaptureError(captureError, { error, request, context });
19
+ } catch {
20
+ // Observability callbacks must not replace the application error Next.js is handling.
21
+ }
22
+ }
23
+ }
24
+ };
25
+ }
26
+
27
+ export default {
28
+ createLogBrewNextRequestErrorHandler
29
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logbrew/next",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Next.js App Router helpers for the public LogBrew JavaScript SDK.",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -28,6 +28,17 @@
28
28
  },
29
29
  "default": "./client.js"
30
30
  },
31
+ "./instrumentation": {
32
+ "import": {
33
+ "types": "./instrumentation.d.ts",
34
+ "default": "./instrumentation.js"
35
+ },
36
+ "require": {
37
+ "types": "./instrumentation.d.cts",
38
+ "default": "./instrumentation.cjs"
39
+ },
40
+ "default": "./instrumentation.js"
41
+ },
31
42
  "./release-artifacts": {
32
43
  "import": {
33
44
  "types": "./release-artifacts.d.ts",
@@ -49,6 +60,10 @@
49
60
  "client.js",
50
61
  "client.d.ts",
51
62
  "client.d.cts",
63
+ "instrumentation.cjs",
64
+ "instrumentation.js",
65
+ "instrumentation.d.ts",
66
+ "instrumentation.d.cts",
52
67
  "release-artifacts.cjs",
53
68
  "release-artifacts.js",
54
69
  "release-artifacts.d.ts",
@@ -82,6 +97,6 @@
82
97
  "react-dom": ">=18"
83
98
  },
84
99
  "scripts": {
85
- "test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/real-user-smoke.mjs && node --test"
100
+ "test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check instrumentation.js && node --check instrumentation.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/request-errors.mjs && node --check examples/real-user-smoke.mjs && node --test"
86
101
  }
87
102
  }