@klnap/next-proxy-chain 1.1.0 → 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.
@@ -73,47 +67,64 @@ 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 and typed rules
70
+ ## Context: data shared along the chain
77
71
 
78
- A handler that needs per-request state is written with `defineProxy()`. It receives a context object as its second argument:
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`:
79
73
 
80
74
  ```ts
81
75
  import { chain, defineProxy, next } from '@klnap/next-proxy-chain'
76
+ import { NextResponse } from 'next/server'
82
77
 
83
- type Session = { user?: string }
78
+ type Session = { user: string }
84
79
 
85
- const readSession = defineProxy<Session>('read-session', (request, session) => {
86
- session.user = request.cookies.get('user')?.value
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 })
87
84
  return next()
88
85
  })
89
86
 
90
- const requireUser = defineProxy<Session>('require-user', (request, session) => {
91
- if (!session.user) return NextResponse.redirect(new URL('/login', request.url))
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))
92
91
  return next()
93
92
  })
94
93
 
95
- export default chain(
96
- [readSession, [requireUser, '/dashboard/**']],
97
- { createContext: (): Session => ({}) }
98
- )
94
+ export default chain([readSession, [requireUser, '/dashboard/**']])
99
95
  ```
100
96
 
101
- - The context is created for each request and is not shared between requests.
102
- - `createContext` is required when a rule declares a context type. Passing a rule that expects a different type is a compile-time error.
103
- - Rules run in array order. Put the rule that sets a value before the rule that reads it.
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)`.
101
+
102
+ ### Optional: `createContext`
104
103
 
105
- Use `defineProxy()` only when you need the context or a named rule. A plain function is enough for everything else.
104
+ `createContext` creates the context object yourself. Use it when every rule should start with the same typed object, such as a request ID:
105
+
106
+ ```ts
107
+ type Ctx = { requestId: string }
108
+
109
+ export default chain([requestLog, authProxy], {
110
+ createContext: (req): Ctx => ({
111
+ requestId: req.headers.get('x-request-id') ?? crypto.randomUUID(),
112
+ }),
113
+ })
114
+ ```
115
+
116
+ Rules declared with `defineProxy<Ctx>` need a matching `createContext`. TypeScript reports an error otherwise.
106
117
 
107
118
  ## Continuing and stopping
108
119
 
109
- | A handler returns | Effect |
110
- | :--- | :--- |
111
- | `undefined` or nothing | Continue. |
112
- | `NextResponse.next()` | Continue. Its request-header overrides are kept. |
113
- | `NextResponse.rewrite(url)` | Continue. The rewrite is applied at the end unless a later handler stops. |
114
- | `NextResponse.redirect(url)`, `NextResponse.json()`, `Response`, `Response.redirect()` | Stop and return that response. |
115
- | `next({ request, headers })` | Continue, and apply the given headers. This is a library token; plain Next.js handlers should return `NextResponse.next()`. |
116
- | 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. |
117
128
 
118
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.
119
130
 
@@ -123,19 +134,150 @@ Headers and cookies that earlier handlers set are kept on the response that stop
123
134
 
124
135
  `chain(entries, options)` accepts the same options as `proxyChain`:
125
136
 
126
- | Option | Purpose |
127
- | :--- | :--- |
128
- | `createContext` | Creates the context for each request. Required for typed rules. |
129
- | `onError` | Returns a `Response` to stop with, `next()` to continue, or nothing for a `500`. |
130
- | `ruleTimeoutMs` | Time limit per handler. `0` (default) disables it. |
131
- | `headerMergeStrategy`, `cookieMergeStrategy` | How conflicting response headers and cookies are resolved. |
132
- | `requestHeaderPolicy` | Which request headers `next({ request })` may set. |
133
- | `debug`, `logger` | One log line per handler, and a custom logger. |
134
- | `strictOverrideCheck` | Throw at startup if Next.js does not apply request overrides. |
135
- | `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. |
136
149
 
137
150
  The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
138
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
+
139
281
  ## Native compatibility
140
282
 
141
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.