@klnap/next-proxy-chain 1.1.1 → 2.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,9 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 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)`.
8
+
9
+ 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.
10
+
11
+ ## 1.2.0
12
+
13
+ ### Minor Changes
14
+
15
+ - d78ef24: Add configurable request diagnostics, structured traces, and named native handlers.
16
+
3
17
  All notable changes to `@klnap/next-proxy-chain` will be documented in this file.
4
18
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
19
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
20
 
21
+ ## [1.1.1] - 2026-11-23
22
+
23
+ ### Documentation
24
+
25
+ - README context section explains `ctx.set` and `ctx.get` with a tested example, and `createContext` as an optional object.
26
+
7
27
  ## [1.1.0] - 2026-11-22
8
28
 
9
29
  ### Added
package/README.md CHANGED
@@ -1,17 +1,11 @@
1
1
  # @klnap/next-proxy-chain
2
2
 
3
- Run several Next.js `proxy.ts` (or `middleware.ts`) handlers as one chain. Each handler can be a plain native Next.js function, scoped to certain paths, and the chain stops or continues according to what each handler returns.
4
-
5
- Next.js exports one proxy per app. As soon as the file contains an auth check, a locale redirect, and some security headers, the order matters and the pieces end up in one long function. This package keeps each handler separate and keeps the order visible.
3
+ Composable proxy and middleware for Next.js.
6
4
 
7
5
  ```ts
8
- import { chain } from '@klnap/next-proxy-chain'
6
+ import { chain } from "@klnap/next-proxy-chain";
9
7
 
10
- export default chain([
11
- intlProxy,
12
- [authProxy, '/dashboard/**'],
13
- securityProxy,
14
- ])
8
+ export default chain([intlProxy, [authProxy, "/dashboard/**"], securityProxy]);
15
9
  ```
16
10
 
17
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.
@@ -31,15 +25,15 @@ bun add @klnap/next-proxy-chain
31
25
  Pass handlers in the order they should run. Each one receives the native `(request, event)` arguments, so `event.waitUntil()` works.
32
26
 
33
27
  ```ts
34
- import { chain } from '@klnap/next-proxy-chain'
35
- import { NextResponse } from 'next/server'
28
+ import { chain } from "@klnap/next-proxy-chain";
29
+ import { NextResponse } from "next/server";
36
30
 
37
31
  function analytics(request, event) {
38
- event.waitUntil(sendPageView(request.nextUrl.pathname))
39
- return NextResponse.next()
32
+ event.waitUntil(sendPageView(request.nextUrl.pathname));
33
+ return NextResponse.next();
40
34
  }
41
35
 
42
- export default chain([analytics, intlProxy, securityProxy])
36
+ export default chain([analytics, intlProxy, securityProxy]);
43
37
  ```
44
38
 
45
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.
@@ -51,17 +45,17 @@ Wrap a handler in a tuple to run it only for some paths or hosts:
51
45
  ```ts
52
46
  export default chain([
53
47
  // Only /dashboard and its children.
54
- [authProxy, '/dashboard/**'],
48
+ [authProxy, "/dashboard/**"],
55
49
 
56
50
  // Everything except /login.
57
- [adminProxy, { exclude: '/admin/login' }],
51
+ [adminProxy, { exclude: "/admin/login" }],
58
52
 
59
53
  // RegExp works too.
60
54
  [privateProxy, { exclude: /^\/public(\/.*)?$/ }],
61
55
 
62
56
  // Several patterns and a host.
63
- [billingProxy, { include: { host: 'app.example.com', path: ['/billing/**', '/invoices/**'] } }],
64
- ])
57
+ [billingProxy, { include: { host: "app.example.com", path: ["/billing/**", "/invoices/**"] } }],
58
+ ]);
65
59
  ```
66
60
 
67
61
  Path patterns:
@@ -73,85 +67,205 @@ Path patterns:
73
67
 
74
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.
75
69
 
76
- ## Context: data shared along the chain
70
+ ## Context: request metadata and shared state
77
71
 
78
- 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`:
72
+ Every invocation gets a unique request ID and immutable metadata. Add an application context type to share mutable state between handlers:
79
73
 
80
74
  ```ts
81
- import { chain, defineProxy, next } from '@klnap/next-proxy-chain'
82
- import { NextResponse } from 'next/server'
75
+ import { chain, defineHandler, next } from "@klnap/next-proxy-chain";
76
+ import { NextResponse } from "next/server";
83
77
 
84
- type Session = { user: string }
78
+ type Context = { session?: { user: string } };
85
79
 
86
- // Sets the value.
87
- const readSession = defineProxy('read-session', (req, ctx) => {
88
- const user = req.cookies.get('user')?.value
89
- if (user) ctx.set('session', { user })
90
- return next()
91
- })
80
+ const readSession = defineHandler<Context>({
81
+ name: "read-session",
82
+ handler: (request, _event, context) => {
83
+ const user = request.cookies.get("user")?.value;
84
+ if (user) context.session = { user };
85
+ return next();
86
+ },
87
+ });
92
88
 
93
89
  // Reads the value.
94
- const requireUser = defineProxy('require-user', (req, ctx) => {
95
- const session = ctx.get('session') as Session | undefined
96
- if (!session) return NextResponse.redirect(new URL('/login', req.url))
97
- return next()
98
- })
99
-
100
- export default chain([readSession, [requireUser, '/dashboard/**']])
90
+ const requireUser = defineHandler<Context>({
91
+ name: "require-user",
92
+ handler: (request, _event, context) => {
93
+ const session = context.session;
94
+ if (!session) return NextResponse.redirect(new URL("/login", request.url));
95
+ return next();
96
+ },
97
+ });
98
+
99
+ export default chain<Context>([readSession, [requireUser, "/dashboard/**"]]);
101
100
  ```
102
101
 
103
- - Each request has its own map. Values never leak between requests.
104
- - `ctx.get` returns `unknown`, so cast it to the type you stored.
102
+ - `requestId`, `startedAt`, `elapsedMs`, `originalUrl`, `originalPathname`, `originalHostname`, and `signal` are read-only.
103
+ - `requestId` is generated by the package and ignores incoming request-ID headers.
104
+ - Application properties are optional until set. Each request gets isolated state.
105
+ - Use a finite-key object type for application state; broad string index signatures make `HandlerContext<T>` resolve to `never`.
105
106
  - Rules run in array order. Set the value before the rule that reads it.
106
- - A native handler reads the same map through its third argument: `(request, event, ctx)`.
107
+ - A native handler reads the same metadata and application state through its third argument: `(request, event, ctx)`.
107
108
 
108
- ### Optional: `createContext`
109
+ ## Continuing and stopping
109
110
 
110
- `createContext` creates the context object yourself. Use it when every rule should start with the same typed object, such as a request ID:
111
+ | A handler returns | Effect |
112
+ | :------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- |
113
+ | `undefined` or nothing | Continue. |
114
+ | `NextResponse.next()` | Continue. Its request-header overrides are kept. |
115
+ | `NextResponse.rewrite(url)` | Continue. The rewrite is applied at the end unless a later handler stops. |
116
+ | `NextResponse.redirect(url)`, `NextResponse.json()`, `Response`, `Response.redirect()` | Stop and return that response. |
117
+ | `next({ request, headers })` | Continue, and apply the given headers. This is a library token; plain Next.js handlers should return `NextResponse.next()`. |
118
+ | A thrown error or a rejected promise | Fail closed with `500`, unless `onError` is set. |
119
+
120
+ 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.
121
+
122
+ Headers and cookies that earlier handlers set are kept on the response that stops the chain. Handlers after it do not contribute.
123
+
124
+ ## Options
125
+
126
+ `chain(entries, options)` accepts these options:
127
+
128
+ | Option | Purpose |
129
+ | :------------------------------------------- | :------------------------------------------------------------------------------- |
130
+ | `onError` | Returns a `Response` to stop with, `next()` to continue, or nothing for a `500`. |
131
+ | `timeout` | Time limit per handler, including its predicate. `0` (default) disables it. |
132
+ | `headerMergeStrategy`, `cookieMergeStrategy` | How conflicting response headers and cookies are resolved. |
133
+ | `requestHeaderPolicy` | Which request headers `next({ request })` may set. |
134
+ | `debug`, `logger` | Built-in diagnostics level and its output sink. Debugging defaults to `false`. |
135
+ | `onTrace` | Optional non-blocking callback with one structured trace per request. |
136
+ | `tracePath` | Include the request pathname in diagnostics. Set `false` to omit it. |
137
+ | `strictOverrideCheck` | Throw at startup if Next.js does not apply request overrides. |
138
+
139
+ The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
140
+
141
+ ## Debugging and observability
142
+
143
+ 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.
111
144
 
112
145
  ```ts
113
- type Ctx = { requestId: string }
146
+ export default chain(handlers, {
147
+ debug: true,
148
+ });
149
+ ```
150
+
151
+ Debug output is off by default, including in development. Set it explicitly:
114
152
 
115
- export default chain([requestLog, authProxy], {
116
- createContext: (req): Ctx => ({
117
- requestId: req.headers.get('x-request-id') ?? crypto.randomUUID(),
118
- }),
119
- })
153
+ ```ts
154
+ export default chain(handlers, {
155
+ debug: process.env.NODE_ENV === "development",
156
+ });
120
157
  ```
121
158
 
122
- Rules declared with `defineProxy<Ctx>` need a matching `createContext`. TypeScript reports an error otherwise.
159
+ `debug` accepts `false`, `true`, `'compact'`, `'detailed'`, or `'verbose'`. `true` means `'detailed'`. Every mode includes the request ID. Compact prints one request summary; detailed adds handler outcomes; verbose adds matching rules and effective timeouts.
123
160
 
124
- ## Continuing and stopping
161
+ Use `defineHandler()` for named handlers with local settings:
125
162
 
126
- | A handler returns | Effect |
127
- | :--- | :--- |
128
- | `undefined` or nothing | Continue. |
129
- | `NextResponse.next()` | Continue. Its request-header overrides are kept. |
130
- | `NextResponse.rewrite(url)` | Continue. The rewrite is applied at the end unless a later handler stops. |
131
- | `NextResponse.redirect(url)`, `NextResponse.json()`, `Response`, `Response.redirect()` | Stop and return that response. |
132
- | `next({ request, headers })` | Continue, and apply the given headers. This is a library token; plain Next.js handlers should return `NextResponse.next()`. |
133
- | A thrown error or a rejected promise | Fail closed with `500`, unless `onError` is set. |
163
+ ```ts
164
+ import { chain, defineHandler } from "@klnap/next-proxy-chain";
165
+
166
+ type Context = { user: string };
167
+
168
+ const authHandler = defineHandler<Context>({
169
+ name: "auth",
170
+ debug: "verbose",
171
+ timeout: 2000,
172
+ rules: {
173
+ include: ["/dashboard/**", "/account/**"],
174
+ exclude: "/account/login",
175
+ },
176
+ handler: (request, event, context) => authenticate(request, event, context),
177
+ });
178
+
179
+ export default chain([authHandler], { debug: "compact" });
180
+ ```
134
181
 
135
- 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.
182
+ 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.
136
183
 
137
- Headers and cookies that earlier handlers set are kept on the response that stops the chain. Handlers after it do not contribute.
184
+ `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.
138
185
 
139
- ## Options
186
+ 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.
140
187
 
141
- `chain(entries, options)` accepts the same options as `proxyChain`:
188
+ ```text
189
+ proxy-chain GET /en/dashboard 1.48ms
190
+ │ ✓ security continue 0.12ms
191
+ │ ✓ session continue 0.84ms
192
+ │ ○ auth skipped
193
+ │ include: /account/** (mismatch)
194
+ │ reason: include-mismatch
195
+ └ NEXT
196
+ ```
142
197
 
143
- | Option | Purpose |
144
- | :--- | :--- |
145
- | `createContext` | Creates the context for each request. Required for typed rules. |
146
- | `onError` | Returns a `Response` to stop with, `next()` to continue, or nothing for a `500`. |
147
- | `ruleTimeoutMs` | Time limit per handler. `0` (default) disables it. |
148
- | `headerMergeStrategy`, `cookieMergeStrategy` | How conflicting response headers and cookies are resolved. |
149
- | `requestHeaderPolicy` | Which request headers `next({ request })` may set. |
150
- | `debug`, `logger` | One log line per handler, and a custom logger. |
151
- | `strictOverrideCheck` | Throw at startup if Next.js does not apply request overrides. |
152
- | `hostFolderHeader` | Opt-in multi-tenant folder prefix for rewrites. |
198
+ ```text
199
+ proxy-chain GET /old-page 0.42ms
200
+ │ ↗ redirects redirect 0.14ms
201
+ │ destination: /new-page
202
+ └ REDIRECT 301 /new-page
203
+ ```
153
204
 
154
- The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
205
+ ```text
206
+ proxy-chain GET /work 1.48ms
207
+ │ ↪ intl rewrite 1.07ms
208
+ │ destination: /en/work
209
+ └ REWRITE /en/work
210
+ ```
211
+
212
+ ```text
213
+ proxy-chain GET /account 2001.24ms
214
+ │ ✓ security continue 0.08ms
215
+ │ × session timeout 2000.00ms
216
+ │ timeout: 2000ms (handler)
217
+ │ error policy: chain default
218
+ │ deadline: 2000ms
219
+ │ – auth not reached
220
+ └ ERROR 500 · timeout 2000ms
221
+ ```
222
+
223
+ ```text
224
+ proxy-chain GET /work 4.72ms
225
+ │ ✓ security continue 0.11ms
226
+ │ ! analytics recovered 4.21ms
227
+ │ error policy: chain
228
+ │ ✓ intl continue 0.24ms
229
+ └ NEXT
230
+ ```
231
+
232
+ Compact output is one line:
233
+
234
+ ```text
235
+ proxy-chain GET /work → NEXT · 3 executed · 1 skipped · 1.48ms
236
+ ```
237
+
238
+ Send traces to any logger without adding a logging dependency:
239
+
240
+ ```ts
241
+ export default chain(handlers, {
242
+ onTrace: (trace) => logger.info(trace),
243
+ });
244
+ ```
245
+
246
+ `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.
247
+
248
+ 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.
249
+
250
+ 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.
251
+
252
+ ### Benchmark
253
+
254
+ 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.
255
+
256
+ 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:
257
+
258
+ | Case | µs/request |
259
+ | :------------------------------------- | ---------: |
260
+ | Debug disabled | 6.61 |
261
+ | Compact | 11.46 |
262
+ | Detailed | 14.79 |
263
+ | Verbose | 20.39 |
264
+ | Structured trace | 10.29 |
265
+ | Detailed, 32 concurrent | 16.45 |
266
+ | Terminal output, compact (10 requests) | 39.63 |
267
+
268
+ Formatting a collected trace alone took 0.59 µs for compact, 3.19 µs for detailed, and 3.54 µs for verbose.
155
269
 
156
270
  ## Native compatibility
157
271
 
@@ -160,8 +274,6 @@ The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain
160
274
  - Handlers can be async.
161
275
  - Handlers returned by other packages work unchanged, if they follow the native signature.
162
276
 
163
- `proxyChain()` is a deprecated alias that is still exported and unchanged. Its plain functions receive `(request, context, event)`. Use `chain()` in new code.
164
-
165
277
  ## Documentation
166
278
 
167
279
  - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): execution order, continuation, scoping, headers, cookies, errors.
@@ -173,15 +285,19 @@ Runnable examples are in [`examples/`](https://github.com/klnap/next-proxy-chain
173
285
 
174
286
  ## Migration
175
287
 
176
- No change is required. `proxyChain()` and `defineProxy()` keep working. To move to `chain()`:
288
+ Version 2 removes `proxyChain()`, `defineProxy()`, context-first handler signatures, and manually constructed rule objects. Upgrade with:
289
+
290
+ 1. Install `@klnap/next-proxy-chain@^2.0.0`.
291
+ 2. Change `proxyChain(options, entries)` to `chain(entries, options)`.
292
+ 3. Replace `defineProxy(name, (request, context, event) => ...)` with `defineHandler({ name, handler: (request, event, context) => ... })`.
293
+ 4. Replace callable scopes such as `handler({ include })` with `[handler, { include }]`, or move the scope into `defineHandler({ rules })`.
294
+ 5. Replace manually constructed `{ run, include, exclude, name }` entries with native functions or `defineHandler()` results.
177
295
 
178
- 1. Replace `proxyChain(entries)` with `chain(entries)`.
179
- 2. Plain functions that used the old `(request, context, event)` signature: rewrite them with `defineProxy()`, which keeps that signature.
180
- 3. Replace `path()` and `host()` helpers with strings, arrays, or objects where you like. They still work.
296
+ Version 1.2 remains backward compatible. Keep using it if you cannot migrate yet.
181
297
 
182
298
  ## Compatibility
183
299
 
184
- - 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.
300
+ - Next.js: peer `>=15.0.0`. CI tests packed ESM, CommonJS, and TypeScript consumers with Next.js 15.5.29 and 16.3.2; CI does not run a live application.
185
301
  - Node.js `>=20`, Bun `>=1`.
186
302
  - 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.
187
303
  - Framework-neutral use (Express, Hono) is not supported. The package depends on Next.js request and response semantics.