@klnap/next-proxy-chain 1.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 149aab5: Simplify the public runtime API to `chain()` and `defineHandler()`, rename configured handlers' executable property from `handler` to `handle`, and remove the package-specific `next()` continuation helper and tuple entries. Use native Next.js responses and request-header replacement semantics for HTTP effects.
8
+
9
+ ### Patch Changes
10
+
11
+ - 2bdae7f: Fix error recovery routing: timeout, request-cancellation, and engine-level recovery now accept only terminal responses, so a recovered `NextResponse.rewrite()` or continuation no longer routes past later handlers. Ordinary errors recovered with a successful rewrite continue as a staged rewrite. Structured traces now record exactly one outcome per handler after a recovered failure. Path matchers keep each alternative's RegExp flags, so `/^\/ABC$/i` matches `/abc`.
12
+
13
+ ## 2.0.0
14
+
15
+ ### Major Changes
16
+
17
+ - 6d431b2: Remove `proxyChain()`, `defineProxy()`, context-first handlers, manually constructed rule objects, legacy public types, and host-folder routing. Use `chain()` with native handlers or `defineHandler()` results. Scoped entries use `[handler, scope]`; chain options use `chain(entries, options)`.
18
+
19
+ Replace Map-backed context and `createContext` with immutable request metadata, generated request IDs, cooperative per-handler cancellation, and typed mutable application state. Rename chain-level `ruleTimeoutMs` to `timeout`; timeout recovery now accepts only terminal responses.
20
+
3
21
  ## 1.2.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -2,320 +2,378 @@
2
2
 
3
3
  Composable proxy and middleware for Next.js.
4
4
 
5
+ Compose security, authentication, redirects, and localization in Next.js's single Proxy or Middleware entrypoint.
6
+
5
7
  ```ts
6
- import { chain } from '@klnap/next-proxy-chain'
8
+ import { chain } from "@klnap/next-proxy-chain";
7
9
 
8
- export default chain([intlProxy, [authProxy, '/dashboard/**'], securityProxy])
10
+ export default chain([security, authentication, redirects, localization]);
9
11
  ```
10
12
 
11
- `intlProxy`, `authProxy` and `securityProxy` are ordinary Next.js proxy functions: `(request, event) => NextResponse | Response | undefined`. You do not wrap them, and you do not change what they return.
13
+ ## Why?
12
14
 
13
- ## Install
15
+ Next.js discovers one Proxy entrypoint. As request logic grows, teams often split authentication, localization, redirects, security headers, and analytics into separate modules.
14
16
 
15
- ```sh
16
- npm install @klnap/next-proxy-chain
17
- # or
17
+ Separate files improve organization. The harder part is agreeing what happens when each handler can continue, rewrite, redirect, or return a response—and which request headers, response headers, and cookies reach the final result.
18
+
19
+ This package composes handlers in order. Handlers keep native `NextRequest`, `NextResponse`, `NextFetchEvent`, and Web `Response` APIs.
20
+
21
+ ## Features
22
+
23
+ - **Native-first composition:** use existing `(request, event)` handlers without wrappers; `event.waitUntil()` keeps the original event.
24
+ - **Ordered execution:** run handlers sequentially; redirects and terminal responses stop later handlers.
25
+ - **Conditional handlers:** match path, host, and asynchronous `when` predicates; keep Next.js `config.matcher` as the outer filter.
26
+ - **Shared request context:** read generated request metadata and share typed, per-request application state.
27
+ - **HTTP composition:** carry native request overrides, response headers, and cookies; continue staged rewrites until a later handler stops.
28
+ - **Execution control:** set per-handler deadlines, pass cooperative `AbortSignal`s, and recover from ordinary errors.
29
+ - **Diagnostics:** inspect formatted request traces or receive structured traces without a logging dependency.
30
+ - **Zero runtime dependencies:** `next` is a peer dependency.
31
+
32
+ ## Installation
33
+
34
+ **Bun**
35
+
36
+ ```bash
18
37
  bun add @klnap/next-proxy-chain
19
38
  ```
20
39
 
21
- `next` is a peer dependency (`>=15.0.0`). The package has no runtime dependencies.
40
+ **npm**
22
41
 
23
- ## Basic composition
42
+ ```bash
43
+ npm install @klnap/next-proxy-chain
44
+ ```
45
+
46
+ ## Usage
24
47
 
25
- Pass handlers in the order they should run. Each one receives the native `(request, event)` arguments, so `event.waitUntil()` works.
48
+ ### Getting started
26
49
 
27
50
  ```ts
28
- import { chain } from '@klnap/next-proxy-chain'
29
- import { NextResponse } from 'next/server'
51
+ import { chain } from "@klnap/next-proxy-chain";
52
+ import { NextResponse, type NextRequest } from "next/server";
30
53
 
31
- function analytics(request, event) {
32
- event.waitUntil(sendPageView(request.nextUrl.pathname))
33
- return NextResponse.next()
54
+ function securityHeaders() {
55
+ const response = NextResponse.next();
56
+ response.headers.set("x-content-type-options", "nosniff");
57
+ return response;
34
58
  }
35
59
 
36
- export default chain([analytics, intlProxy, securityProxy])
37
- ```
60
+ function redirectRoot(request: NextRequest) {
61
+ if (request.nextUrl.pathname === "/") {
62
+ return NextResponse.redirect(new URL("/home", request.url));
63
+ }
64
+ }
38
65
 
39
- A handler continues the chain by returning `undefined` or `NextResponse.next()`. A handler stops the chain by returning a `Response`, `NextResponse.redirect()`, `NextResponse.json()`, or `Response.redirect()`. The rest of this page explains each case.
66
+ export default chain([securityHeaders, redirectRoot]);
40
67
 
41
- ## Scoped handlers
68
+ export const config = {
69
+ matcher: ["/:path*"],
70
+ };
71
+ ```
42
72
 
43
- Wrap a handler in a tuple to run it only for some paths or hosts:
73
+ Save this as `proxy.ts` in Next.js 16 or `middleware.ts` in Next.js 15. The matcher is intentionally broad. Narrow it to routes that need the entrypoint. Next.js reads `config.matcher` statically, so keep it a literal in the file.
44
74
 
45
- ```ts
46
- export default chain([
47
- // Only /dashboard and its children.
48
- [authProxy, '/dashboard/**'],
75
+ `securityHeaders` adds a response header. `redirectRoot` can stop the chain with a redirect. The chain keeps the earlier header on that redirect.
49
76
 
50
- // Everything except /login.
51
- [adminProxy, { exclude: '/admin/login' }],
77
+ | Handler returns | Chain behavior |
78
+ | -------------------------------------- | ---------------------------------- |
79
+ | `undefined` | Continue to the next handler. |
80
+ | `NextResponse.next()` | Compose HTTP effects and continue. |
81
+ | Successful `NextResponse.rewrite(url)` | Stage the rewrite and continue. |
82
+ | `NextResponse.redirect(url)` | Stop and redirect. |
83
+ | Terminal `Response` | Stop and return the response. |
52
84
 
53
- // RegExp works too.
54
- [privateProxy, { exclude: /^\/public(\/.*)?$/ }],
85
+ Both internal and external successful rewrites are staged while the chain continues. Later path scopes and predicates see the rewritten pathname and query. A rewrite does not change the host used for matching; scopes use the effective `host` or `x-forwarded-host` request header. A prior native header replacement of either value changes later host matching. Original request metadata stays unchanged. A later redirect or terminal response replaces the staged rewrite. Only `NextResponse` routing responses are interpreted; a plain `Response` stays terminal.
55
86
 
56
- // Several patterns and a host.
57
- [billingProxy, { include: { host: 'app.example.com', path: ['/billing/**', '/invoices/**'] } }],
58
- ])
59
- ```
87
+ ### Conditional handlers
60
88
 
61
- Path patterns:
89
+ Configured handlers require a non-empty `name` and a `handle` function. `include` runs a handler when any included scope matches. Any matching `exclude` scope takes precedence. Scope alternatives use OR; `host` and `path` within one scope use AND. `when` runs after scope matching and may return a boolean or a promise.
62
90
 
63
- - `*` matches one segment: `/api/*` matches `/api/users`, not `/api/users/123`.
64
- - `**` matches any depth, including zero segments: `/docs/**` matches `/docs` and `/docs/a/b`.
65
- - `:name` matches one segment and does not capture a value.
66
- - A RegExp is matched against the decoded path. Anchor it with `^` and `$` for an exact match.
91
+ ```ts
92
+ import { chain } from "@klnap/next-proxy-chain";
93
+ import { NextResponse } from "next/server";
94
+ import { security, localization } from "@/lib/proxy/handlers";
67
95
 
68
- Segments are compared whole. `/tenant` does not match `/tenant-other`. A pattern such as `/files/*.pdf` throws when the chain is created, because wildcards must be whole segments.
96
+ export default chain([
97
+ security,
98
+ {
99
+ name: "preview",
100
+ rules: {
101
+ include: "/docs/**",
102
+ when: (request) => request.nextUrl.searchParams.has("preview"),
103
+ },
104
+ handle: () => {
105
+ const response = NextResponse.next();
106
+ response.headers.set("cache-control", "no-store");
107
+ return response;
108
+ },
109
+ },
110
+ localization,
111
+ ]);
112
+ ```
69
113
 
70
- ## Context: data shared along the chain
114
+ Path patterns support `*` for one segment and `**` for zero or more segments. `/docs/**` includes `/docs`. `config.matcher` decides whether Next.js invokes the entrypoint; handler rules only filter configured handlers after invocation.
71
115
 
72
- The context is a `Map` that exists for one request. A rule stores a value with `ctx.set`, and a later rule reads it with `ctx.get`:
116
+ For example, this application-owned handler matches either billing path on the billing host, except the health route:
73
117
 
74
118
  ```ts
75
- import { chain, defineProxy, next } from '@klnap/next-proxy-chain'
76
- import { NextResponse } from 'next/server'
77
-
78
- type Session = { user: string }
79
-
80
- // Sets the value.
81
- const readSession = defineProxy('read-session', (req, ctx) => {
82
- const user = req.cookies.get('user')?.value
83
- if (user) ctx.set('session', { user })
84
- return next()
85
- })
86
-
87
- // Reads the value.
88
- const requireUser = defineProxy('require-user', (req, ctx) => {
89
- const session = ctx.get('session') as Session | undefined
90
- if (!session) return NextResponse.redirect(new URL('/login', req.url))
91
- return next()
92
- })
93
-
94
- export default chain([readSession, [requireUser, '/dashboard/**']])
119
+ {
120
+ name: "billing",
121
+ rules: {
122
+ include: {
123
+ host: "billing.example.com",
124
+ path: ["/billing/**", "/invoices/**"],
125
+ },
126
+ exclude: "/billing/health",
127
+ },
128
+ handle: billing,
129
+ }
95
130
  ```
96
131
 
97
- - Each request has its own map. Values never leak between requests.
98
- - `ctx.get` returns `unknown`, so cast it to the type you stored.
99
- - Rules run in array order. Set the value before the rule that reads it.
100
- - A native handler reads the same map through its third argument: `(request, event, ctx)`.
132
+ Matching controls routing, not authorization. Verify permissions in application-owned code, including at the data-access boundary.
101
133
 
102
- ### Optional: `createContext`
134
+ ### Reusable handlers
103
135
 
104
- `createContext` creates the context object yourself. Use it when every rule should start with the same typed object, such as a request ID:
136
+ `defineHandler()` accepts the same configuration as an inline entry. Moving the object into `defineHandler()` does not change its options or implementation.
105
137
 
106
138
  ```ts
107
- type Ctx = { requestId: string }
139
+ import { defineHandler } from "@klnap/next-proxy-chain";
140
+ import { NextResponse } from "next/server";
108
141
 
109
- export default chain([requestLog, authProxy], {
110
- createContext: (req): Ctx => ({
111
- requestId: req.headers.get('x-request-id') ?? crypto.randomUUID(),
112
- }),
113
- })
142
+ export const preview = defineHandler({
143
+ name: "preview",
144
+ rules: {
145
+ include: "/docs/**",
146
+ when: (request) => request.nextUrl.searchParams.has("preview"),
147
+ },
148
+ handle: () => {
149
+ const response = NextResponse.next();
150
+ response.headers.set("cache-control", "no-store");
151
+ return response;
152
+ },
153
+ });
114
154
  ```
115
155
 
116
- Rules declared with `defineProxy<Ctx>` need a matching `createContext`. TypeScript reports an error otherwise.
117
-
118
- ## Continuing and stopping
156
+ Compose it like any other handler:
119
157
 
120
- | A handler returns | Effect |
121
- | :------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- |
122
- | `undefined` or nothing | Continue. |
123
- | `NextResponse.next()` | Continue. Its request-header overrides are kept. |
124
- | `NextResponse.rewrite(url)` | Continue. The rewrite is applied at the end unless a later handler stops. |
125
- | `NextResponse.redirect(url)`, `NextResponse.json()`, `Response`, `Response.redirect()` | Stop and return that response. |
126
- | `next({ request, headers })` | Continue, and apply the given headers. This is a library token; plain Next.js handlers should return `NextResponse.next()`. |
127
- | A thrown error or a rejected promise | Fail closed with `500`, unless `onError` is set. |
158
+ ```ts
159
+ import { chain } from "@klnap/next-proxy-chain";
160
+ import { security, localization } from "@/lib/proxy/handlers";
161
+ import { preview } from "@/lib/proxy/preview";
128
162
 
129
- Stopping is immediate. A handler after a stopping handler does not run, so put checks that must always run before any handler that might answer the request.
163
+ export default chain([security, preview, localization]);
164
+ ```
130
165
 
131
- Headers and cookies that earlier handlers set are kept on the response that stops the chain. Handlers after it do not contribute.
166
+ Inline and reusable configurations share the same `HandlerConfig` type and runtime behavior. `defineHandler()` validates and returns the configuration unchanged; `handle` remains the executable property in both forms.
132
167
 
133
- ## Options
168
+ ### Request context
134
169
 
135
- `chain(entries, options)` accepts the same options as `proxyChain`:
170
+ The chain creates request metadata and a cancellation signal:
136
171
 
137
- | Option | Purpose |
138
- | :------------------------------------------- | :------------------------------------------------------------------------------- |
139
- | `createContext` | Creates the context for each request. Required for typed rules. |
140
- | `onError` | Returns a `Response` to stop with, `next()` to continue, or nothing for a `500`. |
141
- | `ruleTimeoutMs` | Time limit per handler. `0` (default) disables it. |
142
- | `headerMergeStrategy`, `cookieMergeStrategy` | How conflicting response headers and cookies are resolved. |
143
- | `requestHeaderPolicy` | Which request headers `next({ request })` may set. |
144
- | `debug`, `logger` | Built-in diagnostics level and its output sink. Debugging defaults to `false`. |
145
- | `onTrace` | Optional non-blocking callback with one structured trace per request. |
146
- | `tracePath` | Include the request pathname in diagnostics. Set `false` to omit it. |
147
- | `strictOverrideCheck` | Throw at startup if Next.js does not apply request overrides. |
148
- | `hostFolderHeader` | Opt-in multi-tenant folder prefix for rewrites. |
172
+ ```ts
173
+ import { chain } from "@klnap/next-proxy-chain";
149
174
 
150
- The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
175
+ export default chain([
176
+ {
177
+ name: "request-logger",
178
+ handle: (_request, _event, context) => {
179
+ console.info({
180
+ requestId: context.requestId,
181
+ pathname: context.originalPathname,
182
+ elapsedMs: context.elapsedMs,
183
+ });
184
+ },
185
+ },
186
+ ]);
187
+ ```
151
188
 
152
- ## Debugging and observability
189
+ | Property | Type | Description |
190
+ | ------------------ | ------------- | ---------------------------------------------------- |
191
+ | `requestId` | `string` | Generated request identifier with the `req_` prefix. |
192
+ | `startedAt` | `number` | Unix timestamp in milliseconds. |
193
+ | `elapsedMs` | `number` | Monotonic elapsed time. |
194
+ | `originalUrl` | `string` | Original request URL. |
195
+ | `originalPathname` | `string` | Original request pathname. |
196
+ | `originalHostname` | `string` | Original request hostname. |
197
+ | `signal` | `AbortSignal` | Execution-scoped cancellation signal. |
153
198
 
154
- Enable debugging to see how a request moves through the chain, which handlers run, which are skipped, how long they take, and what response the chain ultimately returns.
199
+ Built-in metadata is read-only. Each chain invocation gets a new request ID. Application context is isolated per request and shared between that request's handlers. Custom properties are optional until a handler sets them, so a reader that runs first can observe `undefined`. A matching predicate and its handler share the same execution-scope signal.
155
200
 
156
201
  ```ts
157
- export default chain(handlers, {
158
- debug: true,
159
- })
202
+ import { chain } from "@klnap/next-proxy-chain";
203
+ import { NextResponse } from "next/server";
204
+
205
+ type AppContext = {
206
+ isPreview: boolean;
207
+ };
208
+
209
+ export default chain<AppContext>([
210
+ {
211
+ name: "detect-preview",
212
+ handle: (request, _event, context) => {
213
+ context.isPreview = request.nextUrl.searchParams.has("preview");
214
+ },
215
+ },
216
+ {
217
+ name: "preview-headers",
218
+ handle: (_request, _event, context) => {
219
+ if (!context.isPreview) return;
220
+ const response = NextResponse.next();
221
+ response.headers.set("cache-control", "no-store");
222
+ return response;
223
+ },
224
+ },
225
+ ]);
160
226
  ```
161
227
 
162
- Debug output is off by default, including in development. Set it explicitly:
228
+ Context is not forwarded downstream automatically. To make a request ID visible to route handlers, use Next.js's native request-header forwarding:
163
229
 
164
230
  ```ts
165
- export default chain(handlers, {
166
- debug: process.env.NODE_ENV === 'development',
167
- })
168
- ```
231
+ import { chain } from "@klnap/next-proxy-chain";
232
+ import { NextResponse } from "next/server";
169
233
 
170
- `debug` accepts `false`, `true`, `'compact'`, `'detailed'`, or `'verbose'`. `true` means `'detailed'`. Compact prints one request summary; detailed adds handler outcomes; verbose adds matching rules and effective timeouts.
234
+ export default chain([
235
+ {
236
+ name: "request-id",
237
+ handle: (request, _event, context) => {
238
+ const headers = new Headers(request.headers);
239
+ headers.set("x-request-id", context.requestId);
240
+ return NextResponse.next({
241
+ request: { headers },
242
+ });
243
+ },
244
+ },
245
+ ]);
246
+ ```
171
247
 
172
- Use `defineHandler()` for named handlers with local settings:
248
+ `NextResponse.next({ request: { headers } })` replaces the forwarded request-header set. Cloning `request.headers` preserves existing headers; omitted headers are removed downstream. This changes downstream request headers, not client-facing response headers. Validate client-controlled values and avoid forwarding sensitive headers without a reason. See [Security](docs/security.md#request-headers).
173
249
 
174
- ```ts
175
- import { chain, defineHandler } from '@klnap/next-proxy-chain'
250
+ ### Timeouts and error recovery
176
251
 
177
- type Context = { user: string }
252
+ The chain-level `timeout` sets a deadline in milliseconds for each handler execution. Its default is `0`, which disables timeouts. A handler-level `timeout` overrides the chain default; handler value `0` disables that handler's deadline. The `when` predicate and `handle` share the same deadline.
178
253
 
179
- const authHandler = defineHandler<Context>({
180
- name: 'auth',
181
- debug: 'verbose',
182
- timeout: 2000,
183
- rules: {
184
- include: ['/dashboard/**', '/account/**'],
185
- exclude: '/account/login',
254
+ ```ts
255
+ import { chain } from "@klnap/next-proxy-chain";
256
+
257
+ import { loadRequestSettings } from "@/lib/proxy/settings";
258
+
259
+ export default chain(
260
+ [
261
+ {
262
+ name: "request-settings",
263
+ rules: { include: "/dashboard/**" },
264
+ timeout: 500,
265
+ handle: async (_request, _event, context) => {
266
+ const settings = await loadRequestSettings({ signal: context.signal });
267
+ if (settings.maintenanceMode) {
268
+ return new Response("Service unavailable", { status: 503 });
269
+ }
270
+ },
271
+ },
272
+ ],
273
+ {
274
+ onError: () => new Response("Service unavailable", { status: 503 }),
186
275
  },
187
- handler: (request, event, context) => authenticate(request, event, context),
188
- })
189
-
190
- export default chain([authHandler], { debug: 'compact' })
276
+ );
191
277
  ```
192
278
 
193
- Handler settings override chain settings; chain settings override library defaults. An explicit `debug: false` hides that handler's built-in detail. It does not affect execution or `onTrace`. A handler-level detail override can enable output while global debugging is off.
279
+ Pass `context.signal` to work that supports cooperative cancellation. A timeout or request cancellation stops the chain from waiting, but cannot stop synchronous JavaScript or work that ignores its signal. `event.waitUntil()` work is outside the handler timeout.
194
280
 
195
- `defineHandler` can also set a local `onError`. It replaces the chain-level error handler for that handler; a local failure does not fall through to the global handler.
281
+ For ordinary errors, handler-level `onError` takes precedence over chain-level `onError`. Returning `NextResponse.next()` or a successful `NextResponse.rewrite()` continues after the failed handler. A terminal `Response` stops the chain.
196
282
 
197
- Detailed output distinguishes continuation, rewrites, redirects, terminal responses, rule skips, handlers not reached, recovered errors, failures, and timeouts. `NEXT` means Next.js continues routing; it does not claim the application returned HTTP 200.
283
+ Timeout, request-cancellation, and engine-level recovery accept only a terminal Web `Response`; continuation and `NextResponse.rewrite()` are rejected. Without recovery, a timeout returns `500`. Cancellation stops this chain and returns a native `NextResponse.next()` handoff. Next.js may continue downstream routing, so cancellation is not a fail-closed response.
198
284
 
199
- ```text
200
- proxy-chain GET /en/dashboard 1.48ms
201
- │ ✓ security continue 0.12ms
202
- │ ✓ session continue 0.84ms
203
- │ ○ auth skipped
204
- │ include: /account/** (mismatch)
205
- │ reason: include-mismatch
206
- └ NEXT
207
- ```
285
+ ### Debugging and observability
208
286
 
209
- ```text
210
- proxy-chain GET /old-page 0.42ms
211
- │ ↗ redirects redirect 0.14ms
212
- │ destination: /new-page
213
- └ REDIRECT 301 /new-page
214
- ```
287
+ Debugging defaults to `false`. Set `debug: true` as an alias for `"detailed"`, or choose a mode:
215
288
 
216
- ```text
217
- proxy-chain GET /work 1.48ms
218
- │ ↪ intl rewrite 1.07ms
219
- │ destination: /en/work
220
- └ REWRITE /en/work
221
- ```
289
+ | Mode | Output |
290
+ | ---------- | ------------------------------------- |
291
+ | `compact` | Single-line request summary. |
292
+ | `detailed` | Request summary and handler outcomes. |
293
+ | `verbose` | Matching and execution details. |
222
294
 
223
- ```text
224
- proxy-chain GET /account 2001.24ms
225
- │ ✓ security continue 0.08ms
226
- │ × session timeout 2000.00ms
227
- │ timeout: 2000ms (handler)
228
- │ error policy: chain default
229
- │ deadline: 2000ms
230
- │ – auth not reached
231
- └ ERROR 500 · timeout 2000ms
232
- ```
295
+ These examples show a continuing security handler, a skipped authentication handler, and a staged localization rewrite. Request IDs and durations vary:
233
296
 
234
297
  ```text
235
- proxy-chain GET /work 4.72ms
236
- │ ✓ security continue 0.11ms
237
- │ ! analytics recovered 4.21ms
238
- │ error policy: chain
239
- │ ✓ intl continue 0.24ms
240
- └ NEXT
298
+ [proxy-chain] req_d14c6cf2-962a-400a-8b7f-6e3c45545fc5 · GET /products · REWRITE /pl/products · 4.34ms · 3/3 handlers
241
299
  ```
242
300
 
243
- Compact output is one line:
244
-
245
301
  ```text
246
- proxy-chain GET /work → NEXT · 3 executed · 1 skipped · 1.48ms
302
+ [proxy-chain] GET /products
303
+ Request: req_63491ecd-a382-4cd4-9a88-b1e8575a33c5
304
+ │ ✓ security continue 0.15ms
305
+ │ ○ authentication skipped
306
+ │ ↪ localization rewrite 0.13ms
307
+ └ REWRITE /pl/products
308
+ Total: 0.80ms
247
309
  ```
248
310
 
249
- Send traces to any logger without adding a logging dependency:
311
+ The compact `reached/total` count includes skipped handlers. Handlers after a terminal outcome count only in the total. See the [diagnostics guide](docs/guides.md#diagnostics) for verbose output.
312
+
313
+ Use `onTrace` for structured diagnostics independently of formatted logging:
250
314
 
251
315
  ```ts
316
+ import { chain } from "@klnap/next-proxy-chain";
317
+
252
318
  export default chain(handlers, {
253
- onTrace: (trace) => logger.info(trace),
254
- })
319
+ debug: "detailed",
320
+ onTrace: (trace) => {
321
+ console.info({
322
+ requestId: trace.requestId,
323
+ outcome: trace.outcome.type,
324
+ handlers: trace.handlers,
325
+ });
326
+ },
327
+ });
255
328
  ```
256
329
 
257
- `onTrace` runs once after each request. The chain does not await it. Synchronous failures and rejected promises are ignored, so logging cannot change the response. The `logger` option replaces the built-in terminal sink; it receives one completed formatted block through `info`. It does not receive every handler event.
258
-
259
- Diagnostics omit query strings, headers, bodies, context values, and raw errors. Redirect and rewrite query values are redacted. Set `tracePath: false` when pathnames may contain private data. Names and strings are length-limited and terminal controls are escaped. Color follows `NO_COLOR` first, then `FORCE_COLOR`, then TTY detection; uncertain or non-interactive output stays plain. Unicode symbols fall back to ASCII for C/POSIX or ASCII locales.
260
-
261
- When debugging and tracing are both disabled, the chain does not create trace arrays or read a clock for diagnostics. Handler durations include `when` evaluation and error recovery; total duration also includes composition and response finalization, so handler durations need not sum to the total. Cross-process and external sink ordering is not guaranteed.
330
+ Formatted and structured traces omit header values, cookie values, raw query values, request bodies, application context values, and raw errors.
262
331
 
263
- ### Benchmark
332
+ `tracePath: false` omits only the original request pathname from the top-level trace and formatted request line. Handler scope patterns and sanitized rewrite or redirect destination paths remain visible. Destination query values appear as `?[query]`.
264
333
 
265
- Run `bun run bench/diagnostics.bench.ts` to compare disabled diagnostics, output levels, structured traces, formatter cost, and concurrent requests. Set `BENCH_TERMINAL_IO=1` to measure actual console output separately. Results vary by runtime and host; these are local measurements, not performance guarantees.
334
+ ## Configuration
266
335
 
267
- Sample run: Bun 1.4.4, Node.js 26.13.1, Linux x86_64 under WSL2, Intel Core i3-10105, three handlers, 20,000 measured requests after 1,000 warmups:
336
+ `chain(entries, options?)` accepts native handlers and configured handler objects. Handler-level options are `rules`, `timeout`, `debug`, and `onError`.
268
337
 
269
- | Case | µs/request |
270
- | :--- | ---: |
271
- | Debug disabled | 6.61 |
272
- | Compact | 11.46 |
273
- | Detailed | 14.79 |
274
- | Verbose | 20.39 |
275
- | Structured trace | 10.29 |
276
- | Detailed, 32 concurrent | 16.45 |
277
- | Terminal output, compact (10 requests) | 39.63 |
338
+ | Chain option | Default | Description |
339
+ | --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------- |
340
+ | `timeout` | `0` | Per-handler deadline in milliseconds; `0` disables it. Handler values override the chain value. |
341
+ | `debug` | `false` | Formatted diagnostics. `true` means `"detailed"`; handlers can override the chain level. |
342
+ | `onError` | None | Recovery for ordinary handler errors; handler-level recovery takes precedence. |
343
+ | `onTrace` | None | Callback for structured request traces. |
344
+ | `tracePath` | `true` | Include the original pathname in diagnostics. |
345
+ | `logger` | Console logger (`info`) | Logger with `debug`, `info`, `warn`, and `error` methods. |
346
+ | `headerMergeStrategy` | `"last-write-wins"` | Resolve conflicts between response headers from continued handlers. |
347
+ | `cookieMergeStrategy` | `"last-write-wins"` | Resolve conflicts between cookie identities from continued handlers. |
348
+ | `strictOverrideCheck` | `false` | Throw at chain creation if native request-header override support cannot be verified. |
278
349
 
279
- Formatting a collected trace alone took 0.59 µs for compact, 3.19 µs for detailed, and 3.54 µs for verbose.
350
+ `onTrace`, `tracePath`, `logger`, merge strategies, and `strictOverrideCheck` are chain-level only. See the [API reference](docs/api.md#chain-options) for types and precedence.
280
351
 
281
- ## Native compatibility
352
+ ## Compatibility
282
353
 
283
- - A plain handler gets `(request, event)`, exactly as in a native `proxy.ts`. `chain()` also passes the request context as an optional third argument, which Next.js never uses.
284
- - `export default chain([...])` is the default export that Next.js expects. Put `export const config = { matcher }` next to it as usual.
285
- - Handlers can be async.
286
- - Handlers returned by other packages work unchanged, if they follow the native signature.
354
+ The package declares `next >=15.0.0` as a peer dependency and Node.js `>=20.0.0`. It provides ESM and CommonJS entrypoints with TypeScript declarations.
287
355
 
288
- `proxyChain()` is a deprecated alias that is still exported and unchanged. Its plain functions receive `(request, context, event)`. Use `chain()` in new code.
356
+ Packed consumer builds and live requests were verified with Next.js 15.5.29 and 16.3.2 on Node.js 26.13.1. This does not verify every version in the peer range. Next.js 15 Edge deployments have not been independently verified.
289
357
 
290
358
  ## Documentation
291
359
 
292
- - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): execution order, continuation, scoping, headers, cookies, errors.
293
- - [Guides](https://github.com/klnap/next-proxy-chain/blob/main/docs/guides.md): recipes for common tasks.
294
- - [API reference](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md): every export and option.
295
- - [Security](https://github.com/klnap/next-proxy-chain/blob/main/docs/security.md): trust boundaries and safe usage.
296
-
297
- Runnable examples are in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/).
298
-
299
- ## Migration
300
-
301
- No change is required. `proxyChain()` and `defineProxy()` keep working. To move to `chain()`:
360
+ - [Concepts](docs/concepts.md) — execution model, matching, rewrites, HTTP composition, and context.
361
+ - [Guides](docs/guides.md) — practical integration examples, request IDs, cancellation, and diagnostics.
362
+ - [API reference](docs/api.md) — public exports, configuration, types, defaults, and precedence.
363
+ - [Security](docs/security.md) — trust boundaries, limitations, and safe integration.
302
364
 
303
- 1. Replace `proxyChain(entries)` with `chain(entries)`.
304
- 2. Plain functions that used the old `(request, context, event)` signature: rewrite them with `defineProxy()`, which keeps that signature.
305
- 3. Replace `path()` and `host()` helpers with strings, arrays, or objects where you like. They still work.
365
+ ### AI coding agents
306
366
 
307
- ## Compatibility
308
-
309
- - Next.js: peer `>=15.0.0`. The test suite runs against Next.js 16.3.2 through a live app. Next.js 15 is covered by integration tests that model its behavior; it has not been run as a live application.
310
- - Node.js `>=20`, Bun `>=1`.
311
- - Next.js 16 runs `proxy.ts` on the Node.js runtime by default. The package uses only Web platform APIs, so it should also run on the Edge runtime for Next.js 15 `middleware.ts`, but that is not tested here.
312
- - Framework-neutral use (Express, Hono) is not supported. The package depends on Next.js request and response semantics.
367
+ The package tarball includes version-matched consumer documentation and public declarations. Read [`llms.txt`](llms.txt) from the installed package at `node_modules/@klnap/next-proxy-chain/`.
313
368
 
314
- ## Links
369
+ ```text
370
+ Before integrating @klnap/next-proxy-chain, read the
371
+ installed package's llms.txt, README.md, relevant
372
+ documentation, and public TypeScript declarations.
315
373
 
316
- - [Changelog](https://github.com/klnap/next-proxy-chain/blob/main/CHANGELOG.md)
317
- - [Issues](https://github.com/klnap/next-proxy-chain/issues)
374
+ Use the installed package's API as the source of truth.
375
+ ```
318
376
 
319
377
  ## License
320
378
 
321
- [MIT](https://github.com/klnap/next-proxy-chain/blob/main/LICENSE)
379
+ [MIT](LICENSE)