@klnap/next-proxy-chain 1.2.0 → 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,5 +1,13 @@
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
+
3
11
  ## 1.2.0
4
12
 
5
13
  ### Minor Changes
package/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  Composable proxy and middleware for Next.js.
4
4
 
5
5
  ```ts
6
- import { chain } from '@klnap/next-proxy-chain'
6
+ import { chain } from "@klnap/next-proxy-chain";
7
7
 
8
- export default chain([intlProxy, [authProxy, '/dashboard/**'], securityProxy])
8
+ export default chain([intlProxy, [authProxy, "/dashboard/**"], securityProxy]);
9
9
  ```
10
10
 
11
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.
@@ -25,15 +25,15 @@ bun add @klnap/next-proxy-chain
25
25
  Pass handlers in the order they should run. Each one receives the native `(request, event)` arguments, so `event.waitUntil()` works.
26
26
 
27
27
  ```ts
28
- import { chain } from '@klnap/next-proxy-chain'
29
- import { NextResponse } from 'next/server'
28
+ import { chain } from "@klnap/next-proxy-chain";
29
+ import { NextResponse } from "next/server";
30
30
 
31
31
  function analytics(request, event) {
32
- event.waitUntil(sendPageView(request.nextUrl.pathname))
33
- return NextResponse.next()
32
+ event.waitUntil(sendPageView(request.nextUrl.pathname));
33
+ return NextResponse.next();
34
34
  }
35
35
 
36
- export default chain([analytics, intlProxy, securityProxy])
36
+ export default chain([analytics, intlProxy, securityProxy]);
37
37
  ```
38
38
 
39
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.
@@ -45,17 +45,17 @@ Wrap a handler in a tuple to run it only for some paths or hosts:
45
45
  ```ts
46
46
  export default chain([
47
47
  // Only /dashboard and its children.
48
- [authProxy, '/dashboard/**'],
48
+ [authProxy, "/dashboard/**"],
49
49
 
50
50
  // Everything except /login.
51
- [adminProxy, { exclude: '/admin/login' }],
51
+ [adminProxy, { exclude: "/admin/login" }],
52
52
 
53
53
  // RegExp works too.
54
54
  [privateProxy, { exclude: /^\/public(\/.*)?$/ }],
55
55
 
56
56
  // Several patterns and a host.
57
- [billingProxy, { include: { host: 'app.example.com', path: ['/billing/**', '/invoices/**'] } }],
58
- ])
57
+ [billingProxy, { include: { host: "app.example.com", path: ["/billing/**", "/invoices/**"] } }],
58
+ ]);
59
59
  ```
60
60
 
61
61
  Path patterns:
@@ -67,53 +67,44 @@ Path patterns:
67
67
 
68
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.
69
69
 
70
- ## Context: data shared along the chain
70
+ ## Context: request metadata and shared state
71
71
 
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`:
72
+ Every invocation gets a unique request ID and immutable metadata. Add an application context type to share mutable state between handlers:
73
73
 
74
74
  ```ts
75
- import { chain, defineProxy, next } from '@klnap/next-proxy-chain'
76
- import { NextResponse } from 'next/server'
75
+ import { chain, defineHandler, next } from "@klnap/next-proxy-chain";
76
+ import { NextResponse } from "next/server";
77
77
 
78
- type Session = { user: string }
78
+ type Context = { session?: { user: string } };
79
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
- })
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
+ });
86
88
 
87
89
  // 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
- })
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
+ });
93
98
 
94
- export default chain([readSession, [requireUser, '/dashboard/**']])
99
+ export default chain<Context>([readSession, [requireUser, "/dashboard/**"]]);
95
100
  ```
96
101
 
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.
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`.
99
106
  - 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`
103
-
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.
107
+ - A native handler reads the same metadata and application state through its third argument: `(request, event, ctx)`.
117
108
 
118
109
  ## Continuing and stopping
119
110
 
@@ -132,20 +123,18 @@ Headers and cookies that earlier handlers set are kept on the response that stop
132
123
 
133
124
  ## Options
134
125
 
135
- `chain(entries, options)` accepts the same options as `proxyChain`:
126
+ `chain(entries, options)` accepts these options:
136
127
 
137
128
  | Option | Purpose |
138
129
  | :------------------------------------------- | :------------------------------------------------------------------------------- |
139
- | `createContext` | Creates the context for each request. Required for typed rules. |
140
130
  | `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. |
131
+ | `timeout` | Time limit per handler, including its predicate. `0` (default) disables it. |
142
132
  | `headerMergeStrategy`, `cookieMergeStrategy` | How conflicting response headers and cookies are resolved. |
143
133
  | `requestHeaderPolicy` | Which request headers `next({ request })` may set. |
144
134
  | `debug`, `logger` | Built-in diagnostics level and its output sink. Debugging defaults to `false`. |
145
135
  | `onTrace` | Optional non-blocking callback with one structured trace per request. |
146
136
  | `tracePath` | Include the request pathname in diagnostics. Set `false` to omit it. |
147
137
  | `strictOverrideCheck` | Throw at startup if Next.js does not apply request overrides. |
148
- | `hostFolderHeader` | Opt-in multi-tenant folder prefix for rewrites. |
149
138
 
150
139
  The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
151
140
 
@@ -156,38 +145,38 @@ Enable debugging to see how a request moves through the chain, which handlers ru
156
145
  ```ts
157
146
  export default chain(handlers, {
158
147
  debug: true,
159
- })
148
+ });
160
149
  ```
161
150
 
162
151
  Debug output is off by default, including in development. Set it explicitly:
163
152
 
164
153
  ```ts
165
154
  export default chain(handlers, {
166
- debug: process.env.NODE_ENV === 'development',
167
- })
155
+ debug: process.env.NODE_ENV === "development",
156
+ });
168
157
  ```
169
158
 
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.
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.
171
160
 
172
161
  Use `defineHandler()` for named handlers with local settings:
173
162
 
174
163
  ```ts
175
- import { chain, defineHandler } from '@klnap/next-proxy-chain'
164
+ import { chain, defineHandler } from "@klnap/next-proxy-chain";
176
165
 
177
- type Context = { user: string }
166
+ type Context = { user: string };
178
167
 
179
168
  const authHandler = defineHandler<Context>({
180
- name: 'auth',
181
- debug: 'verbose',
169
+ name: "auth",
170
+ debug: "verbose",
182
171
  timeout: 2000,
183
172
  rules: {
184
- include: ['/dashboard/**', '/account/**'],
185
- exclude: '/account/login',
173
+ include: ["/dashboard/**", "/account/**"],
174
+ exclude: "/account/login",
186
175
  },
187
176
  handler: (request, event, context) => authenticate(request, event, context),
188
- })
177
+ });
189
178
 
190
- export default chain([authHandler], { debug: 'compact' })
179
+ export default chain([authHandler], { debug: "compact" });
191
180
  ```
192
181
 
193
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.
@@ -251,7 +240,7 @@ Send traces to any logger without adding a logging dependency:
251
240
  ```ts
252
241
  export default chain(handlers, {
253
242
  onTrace: (trace) => logger.info(trace),
254
- })
243
+ });
255
244
  ```
256
245
 
257
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.
@@ -266,15 +255,15 @@ Run `bun run bench/diagnostics.bench.ts` to compare disabled diagnostics, output
266
255
 
267
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:
268
257
 
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 |
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 |
278
267
 
279
268
  Formatting a collected trace alone took 0.59 µs for compact, 3.19 µs for detailed, and 3.54 µs for verbose.
280
269
 
@@ -285,8 +274,6 @@ Formatting a collected trace alone took 0.59 µs for compact, 3.19 µs for detai
285
274
  - Handlers can be async.
286
275
  - Handlers returned by other packages work unchanged, if they follow the native signature.
287
276
 
288
- `proxyChain()` is a deprecated alias that is still exported and unchanged. Its plain functions receive `(request, context, event)`. Use `chain()` in new code.
289
-
290
277
  ## Documentation
291
278
 
292
279
  - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): execution order, continuation, scoping, headers, cookies, errors.
@@ -298,15 +285,19 @@ Runnable examples are in [`examples/`](https://github.com/klnap/next-proxy-chain
298
285
 
299
286
  ## Migration
300
287
 
301
- 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.
302
295
 
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.
296
+ Version 1.2 remains backward compatible. Keep using it if you cannot migrate yet.
306
297
 
307
298
  ## Compatibility
308
299
 
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.
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.
310
301
  - Node.js `>=20`, Bun `>=1`.
311
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.
312
303
  - Framework-neutral use (Express, Hono) is not supported. The package depends on Next.js request and response semantics.