@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 +20 -0
- package/README.md +195 -79
- package/dist/index.cjs +956 -258
- package/dist/index.d.cts +164 -82
- package/dist/index.d.ts +164 -82
- package/dist/index.js +954 -254
- package/package.json +35 -22
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
|
-
|
|
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
|
|
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
|
|
35
|
-
import { NextResponse } from
|
|
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,
|
|
48
|
+
[authProxy, "/dashboard/**"],
|
|
55
49
|
|
|
56
50
|
// Everything except /login.
|
|
57
|
-
[adminProxy, { exclude:
|
|
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:
|
|
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:
|
|
70
|
+
## Context: request metadata and shared state
|
|
77
71
|
|
|
78
|
-
|
|
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,
|
|
82
|
-
import { NextResponse } from
|
|
75
|
+
import { chain, defineHandler, next } from "@klnap/next-proxy-chain";
|
|
76
|
+
import { NextResponse } from "next/server";
|
|
83
77
|
|
|
84
|
-
type
|
|
78
|
+
type Context = { session?: { user: string } };
|
|
85
79
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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 =
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
-
|
|
104
|
-
- `
|
|
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
|
|
107
|
+
- A native handler reads the same metadata and application state through its third argument: `(request, event, ctx)`.
|
|
107
108
|
|
|
108
|
-
|
|
109
|
+
## Continuing and stopping
|
|
109
110
|
|
|
110
|
-
|
|
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
|
-
|
|
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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
})
|
|
153
|
+
```ts
|
|
154
|
+
export default chain(handlers, {
|
|
155
|
+
debug: process.env.NODE_ENV === "development",
|
|
156
|
+
});
|
|
120
157
|
```
|
|
121
158
|
|
|
122
|
-
|
|
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
|
-
|
|
161
|
+
Use `defineHandler()` for named handlers with local settings:
|
|
125
162
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
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`.
|
|
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.
|