@klnap/next-proxy-chain 1.1.1 → 1.2.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,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - d78ef24: Add configurable request diagnostics, structured traces, and named native handlers.
8
+
3
9
  All notable changes to `@klnap/next-proxy-chain` will be documented in this file.
4
10
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
11
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
12
 
13
+ ## [1.1.1] - 2026-11-23
14
+
15
+ ### Documentation
16
+
17
+ - README context section explains `ctx.set` and `ctx.get` with a tested example, and `createContext` as an optional object.
18
+
7
19
  ## [1.1.0] - 2026-11-22
8
20
 
9
21
  ### 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
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.
@@ -123,14 +117,14 @@ Rules declared with `defineProxy<Ctx>` need a matching `createContext`. TypeScri
123
117
 
124
118
  ## Continuing and stopping
125
119
 
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. |
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. |
134
128
 
135
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.
136
130
 
@@ -140,19 +134,150 @@ Headers and cookies that earlier handlers set are kept on the response that stop
140
134
 
141
135
  `chain(entries, options)` accepts the same options as `proxyChain`:
142
136
 
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. |
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. |
153
149
 
154
150
  The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
155
151
 
152
+ ## Debugging and observability
153
+
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.
155
+
156
+ ```ts
157
+ export default chain(handlers, {
158
+ debug: true,
159
+ })
160
+ ```
161
+
162
+ Debug output is off by default, including in development. Set it explicitly:
163
+
164
+ ```ts
165
+ export default chain(handlers, {
166
+ debug: process.env.NODE_ENV === 'development',
167
+ })
168
+ ```
169
+
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.
171
+
172
+ Use `defineHandler()` for named handlers with local settings:
173
+
174
+ ```ts
175
+ import { chain, defineHandler } from '@klnap/next-proxy-chain'
176
+
177
+ type Context = { user: string }
178
+
179
+ const authHandler = defineHandler<Context>({
180
+ name: 'auth',
181
+ debug: 'verbose',
182
+ timeout: 2000,
183
+ rules: {
184
+ include: ['/dashboard/**', '/account/**'],
185
+ exclude: '/account/login',
186
+ },
187
+ handler: (request, event, context) => authenticate(request, event, context),
188
+ })
189
+
190
+ export default chain([authHandler], { debug: 'compact' })
191
+ ```
192
+
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.
194
+
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.
196
+
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.
198
+
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
+ ```
208
+
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
+ ```
215
+
216
+ ```text
217
+ proxy-chain GET /work 1.48ms
218
+ │ ↪ intl rewrite 1.07ms
219
+ │ destination: /en/work
220
+ └ REWRITE /en/work
221
+ ```
222
+
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
+ ```
233
+
234
+ ```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
241
+ ```
242
+
243
+ Compact output is one line:
244
+
245
+ ```text
246
+ proxy-chain GET /work → NEXT · 3 executed · 1 skipped · 1.48ms
247
+ ```
248
+
249
+ Send traces to any logger without adding a logging dependency:
250
+
251
+ ```ts
252
+ export default chain(handlers, {
253
+ onTrace: (trace) => logger.info(trace),
254
+ })
255
+ ```
256
+
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.
262
+
263
+ ### Benchmark
264
+
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.
266
+
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:
268
+
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 |
278
+
279
+ Formatting a collected trace alone took 0.59 µs for compact, 3.19 µs for detailed, and 3.54 µs for verbose.
280
+
156
281
  ## Native compatibility
157
282
 
158
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.