@klnap/next-proxy-chain 2.0.0 → 3.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 +10 -0
- package/README.md +272 -205
- package/dist/index.cjs +83 -201
- package/dist/index.d.cts +32 -101
- package/dist/index.d.ts +32 -101
- package/dist/index.js +82 -195
- package/docs/api.md +190 -0
- package/docs/concepts.md +88 -0
- package/docs/guides.md +210 -0
- package/docs/security.md +104 -0
- package/llms.txt +17 -0
- package/package.json +7 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 149aab5: Simplify the public runtime API to `chain()` and `defineHandler()`, rename configured handlers' executable property from `handler` to `handle`, and remove the package-specific `next()` continuation helper and tuple entries. Use native Next.js responses and request-header replacement semantics for HTTP effects.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 2bdae7f: Fix error recovery routing: timeout, request-cancellation, and engine-level recovery now accept only terminal responses, so a recovered `NextResponse.rewrite()` or continuation no longer routes past later handlers. Ordinary errors recovered with a successful rewrite continue as a staged rewrite. Structured traces now record exactly one outcome per handler after a recovered failure. Path matchers keep each alternative's RegExp flags, so `/^\/ABC$/i` matches `/abc`.
|
|
12
|
+
|
|
3
13
|
## 2.0.0
|
|
4
14
|
|
|
5
15
|
### Major Changes
|
package/README.md
CHANGED
|
@@ -2,311 +2,378 @@
|
|
|
2
2
|
|
|
3
3
|
Composable proxy and middleware for Next.js.
|
|
4
4
|
|
|
5
|
+
Compose security, authentication, redirects, and localization in Next.js's single Proxy or Middleware entrypoint.
|
|
6
|
+
|
|
5
7
|
```ts
|
|
6
8
|
import { chain } from "@klnap/next-proxy-chain";
|
|
7
9
|
|
|
8
|
-
export default chain([
|
|
10
|
+
export default chain([security, authentication, redirects, localization]);
|
|
9
11
|
```
|
|
10
12
|
|
|
11
|
-
|
|
13
|
+
## Why?
|
|
12
14
|
|
|
13
|
-
|
|
15
|
+
Next.js discovers one Proxy entrypoint. As request logic grows, teams often split authentication, localization, redirects, security headers, and analytics into separate modules.
|
|
14
16
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
Separate files improve organization. The harder part is agreeing what happens when each handler can continue, rewrite, redirect, or return a response—and which request headers, response headers, and cookies reach the final result.
|
|
18
|
+
|
|
19
|
+
This package composes handlers in order. Handlers keep native `NextRequest`, `NextResponse`, `NextFetchEvent`, and Web `Response` APIs.
|
|
20
|
+
|
|
21
|
+
## Features
|
|
22
|
+
|
|
23
|
+
- **Native-first composition:** use existing `(request, event)` handlers without wrappers; `event.waitUntil()` keeps the original event.
|
|
24
|
+
- **Ordered execution:** run handlers sequentially; redirects and terminal responses stop later handlers.
|
|
25
|
+
- **Conditional handlers:** match path, host, and asynchronous `when` predicates; keep Next.js `config.matcher` as the outer filter.
|
|
26
|
+
- **Shared request context:** read generated request metadata and share typed, per-request application state.
|
|
27
|
+
- **HTTP composition:** carry native request overrides, response headers, and cookies; continue staged rewrites until a later handler stops.
|
|
28
|
+
- **Execution control:** set per-handler deadlines, pass cooperative `AbortSignal`s, and recover from ordinary errors.
|
|
29
|
+
- **Diagnostics:** inspect formatted request traces or receive structured traces without a logging dependency.
|
|
30
|
+
- **Zero runtime dependencies:** `next` is a peer dependency.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
**Bun**
|
|
35
|
+
|
|
36
|
+
```bash
|
|
18
37
|
bun add @klnap/next-proxy-chain
|
|
19
38
|
```
|
|
20
39
|
|
|
21
|
-
|
|
40
|
+
**npm**
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm install @klnap/next-proxy-chain
|
|
44
|
+
```
|
|
22
45
|
|
|
23
|
-
##
|
|
46
|
+
## Usage
|
|
24
47
|
|
|
25
|
-
|
|
48
|
+
### Getting started
|
|
26
49
|
|
|
27
50
|
```ts
|
|
28
51
|
import { chain } from "@klnap/next-proxy-chain";
|
|
29
|
-
import { NextResponse } from "next/server";
|
|
52
|
+
import { NextResponse, type NextRequest } from "next/server";
|
|
30
53
|
|
|
31
|
-
function
|
|
32
|
-
|
|
33
|
-
|
|
54
|
+
function securityHeaders() {
|
|
55
|
+
const response = NextResponse.next();
|
|
56
|
+
response.headers.set("x-content-type-options", "nosniff");
|
|
57
|
+
return response;
|
|
34
58
|
}
|
|
35
59
|
|
|
36
|
-
|
|
60
|
+
function redirectRoot(request: NextRequest) {
|
|
61
|
+
if (request.nextUrl.pathname === "/") {
|
|
62
|
+
return NextResponse.redirect(new URL("/home", request.url));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export default chain([securityHeaders, redirectRoot]);
|
|
67
|
+
|
|
68
|
+
export const config = {
|
|
69
|
+
matcher: ["/:path*"],
|
|
70
|
+
};
|
|
37
71
|
```
|
|
38
72
|
|
|
39
|
-
|
|
73
|
+
Save this as `proxy.ts` in Next.js 16 or `middleware.ts` in Next.js 15. The matcher is intentionally broad. Narrow it to routes that need the entrypoint. Next.js reads `config.matcher` statically, so keep it a literal in the file.
|
|
40
74
|
|
|
41
|
-
|
|
75
|
+
`securityHeaders` adds a response header. `redirectRoot` can stop the chain with a redirect. The chain keeps the earlier header on that redirect.
|
|
42
76
|
|
|
43
|
-
|
|
77
|
+
| Handler returns | Chain behavior |
|
|
78
|
+
| -------------------------------------- | ---------------------------------- |
|
|
79
|
+
| `undefined` | Continue to the next handler. |
|
|
80
|
+
| `NextResponse.next()` | Compose HTTP effects and continue. |
|
|
81
|
+
| Successful `NextResponse.rewrite(url)` | Stage the rewrite and continue. |
|
|
82
|
+
| `NextResponse.redirect(url)` | Stop and redirect. |
|
|
83
|
+
| Terminal `Response` | Stop and return the response. |
|
|
44
84
|
|
|
45
|
-
|
|
46
|
-
export default chain([
|
|
47
|
-
// Only /dashboard and its children.
|
|
48
|
-
[authProxy, "/dashboard/**"],
|
|
85
|
+
Both internal and external successful rewrites are staged while the chain continues. Later path scopes and predicates see the rewritten pathname and query. A rewrite does not change the host used for matching; scopes use the effective `host` or `x-forwarded-host` request header. A prior native header replacement of either value changes later host matching. Original request metadata stays unchanged. A later redirect or terminal response replaces the staged rewrite. Only `NextResponse` routing responses are interpreted; a plain `Response` stays terminal.
|
|
49
86
|
|
|
50
|
-
|
|
51
|
-
[adminProxy, { exclude: "/admin/login" }],
|
|
87
|
+
### Conditional handlers
|
|
52
88
|
|
|
53
|
-
|
|
54
|
-
[privateProxy, { exclude: /^\/public(\/.*)?$/ }],
|
|
89
|
+
Configured handlers require a non-empty `name` and a `handle` function. `include` runs a handler when any included scope matches. Any matching `exclude` scope takes precedence. Scope alternatives use OR; `host` and `path` within one scope use AND. `when` runs after scope matching and may return a boolean or a promise.
|
|
55
90
|
|
|
56
|
-
|
|
57
|
-
|
|
91
|
+
```ts
|
|
92
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
93
|
+
import { NextResponse } from "next/server";
|
|
94
|
+
import { security, localization } from "@/lib/proxy/handlers";
|
|
95
|
+
|
|
96
|
+
export default chain([
|
|
97
|
+
security,
|
|
98
|
+
{
|
|
99
|
+
name: "preview",
|
|
100
|
+
rules: {
|
|
101
|
+
include: "/docs/**",
|
|
102
|
+
when: (request) => request.nextUrl.searchParams.has("preview"),
|
|
103
|
+
},
|
|
104
|
+
handle: () => {
|
|
105
|
+
const response = NextResponse.next();
|
|
106
|
+
response.headers.set("cache-control", "no-store");
|
|
107
|
+
return response;
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
localization,
|
|
58
111
|
]);
|
|
59
112
|
```
|
|
60
113
|
|
|
61
|
-
Path patterns
|
|
114
|
+
Path patterns support `*` for one segment and `**` for zero or more segments. `/docs/**` includes `/docs`. `config.matcher` decides whether Next.js invokes the entrypoint; handler rules only filter configured handlers after invocation.
|
|
62
115
|
|
|
63
|
-
-
|
|
64
|
-
- `**` matches any depth, including zero segments: `/docs/**` matches `/docs` and `/docs/a/b`.
|
|
65
|
-
- `:name` matches one segment and does not capture a value.
|
|
66
|
-
- A RegExp is matched against the decoded path. Anchor it with `^` and `$` for an exact match.
|
|
116
|
+
For example, this application-owned handler matches either billing path on the billing host, except the health route:
|
|
67
117
|
|
|
68
|
-
|
|
118
|
+
```ts
|
|
119
|
+
{
|
|
120
|
+
name: "billing",
|
|
121
|
+
rules: {
|
|
122
|
+
include: {
|
|
123
|
+
host: "billing.example.com",
|
|
124
|
+
path: ["/billing/**", "/invoices/**"],
|
|
125
|
+
},
|
|
126
|
+
exclude: "/billing/health",
|
|
127
|
+
},
|
|
128
|
+
handle: billing,
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Matching controls routing, not authorization. Verify permissions in application-owned code, including at the data-access boundary.
|
|
69
133
|
|
|
70
|
-
|
|
134
|
+
### Reusable handlers
|
|
71
135
|
|
|
72
|
-
|
|
136
|
+
`defineHandler()` accepts the same configuration as an inline entry. Moving the object into `defineHandler()` does not change its options or implementation.
|
|
73
137
|
|
|
74
138
|
```ts
|
|
75
|
-
import {
|
|
139
|
+
import { defineHandler } from "@klnap/next-proxy-chain";
|
|
76
140
|
import { NextResponse } from "next/server";
|
|
77
141
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const user = request.cookies.get("user")?.value;
|
|
84
|
-
if (user) context.session = { user };
|
|
85
|
-
return next();
|
|
142
|
+
export const preview = defineHandler({
|
|
143
|
+
name: "preview",
|
|
144
|
+
rules: {
|
|
145
|
+
include: "/docs/**",
|
|
146
|
+
when: (request) => request.nextUrl.searchParams.has("preview"),
|
|
86
147
|
},
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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();
|
|
148
|
+
handle: () => {
|
|
149
|
+
const response = NextResponse.next();
|
|
150
|
+
response.headers.set("cache-control", "no-store");
|
|
151
|
+
return response;
|
|
96
152
|
},
|
|
97
153
|
});
|
|
98
|
-
|
|
99
|
-
export default chain<Context>([readSession, [requireUser, "/dashboard/**"]]);
|
|
100
154
|
```
|
|
101
155
|
|
|
102
|
-
|
|
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`.
|
|
106
|
-
- Rules run in array order. Set the value before the rule that reads it.
|
|
107
|
-
- A native handler reads the same metadata and application state through its third argument: `(request, event, ctx)`.
|
|
156
|
+
Compose it like any other handler:
|
|
108
157
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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. |
|
|
158
|
+
```ts
|
|
159
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
160
|
+
import { security, localization } from "@/lib/proxy/handlers";
|
|
161
|
+
import { preview } from "@/lib/proxy/preview";
|
|
119
162
|
|
|
120
|
-
|
|
163
|
+
export default chain([security, preview, localization]);
|
|
164
|
+
```
|
|
121
165
|
|
|
122
|
-
|
|
166
|
+
Inline and reusable configurations share the same `HandlerConfig` type and runtime behavior. `defineHandler()` validates and returns the configuration unchanged; `handle` remains the executable property in both forms.
|
|
123
167
|
|
|
124
|
-
|
|
168
|
+
### Request context
|
|
125
169
|
|
|
126
|
-
|
|
170
|
+
The chain creates request metadata and a cancellation signal:
|
|
127
171
|
|
|
128
|
-
|
|
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. |
|
|
172
|
+
```ts
|
|
173
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
138
174
|
|
|
139
|
-
|
|
175
|
+
export default chain([
|
|
176
|
+
{
|
|
177
|
+
name: "request-logger",
|
|
178
|
+
handle: (_request, _event, context) => {
|
|
179
|
+
console.info({
|
|
180
|
+
requestId: context.requestId,
|
|
181
|
+
pathname: context.originalPathname,
|
|
182
|
+
elapsedMs: context.elapsedMs,
|
|
183
|
+
});
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
]);
|
|
187
|
+
```
|
|
140
188
|
|
|
141
|
-
|
|
189
|
+
| Property | Type | Description |
|
|
190
|
+
| ------------------ | ------------- | ---------------------------------------------------- |
|
|
191
|
+
| `requestId` | `string` | Generated request identifier with the `req_` prefix. |
|
|
192
|
+
| `startedAt` | `number` | Unix timestamp in milliseconds. |
|
|
193
|
+
| `elapsedMs` | `number` | Monotonic elapsed time. |
|
|
194
|
+
| `originalUrl` | `string` | Original request URL. |
|
|
195
|
+
| `originalPathname` | `string` | Original request pathname. |
|
|
196
|
+
| `originalHostname` | `string` | Original request hostname. |
|
|
197
|
+
| `signal` | `AbortSignal` | Execution-scoped cancellation signal. |
|
|
142
198
|
|
|
143
|
-
|
|
199
|
+
Built-in metadata is read-only. Each chain invocation gets a new request ID. Application context is isolated per request and shared between that request's handlers. Custom properties are optional until a handler sets them, so a reader that runs first can observe `undefined`. A matching predicate and its handler share the same execution-scope signal.
|
|
144
200
|
|
|
145
201
|
```ts
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
202
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
203
|
+
import { NextResponse } from "next/server";
|
|
204
|
+
|
|
205
|
+
type AppContext = {
|
|
206
|
+
isPreview: boolean;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
export default chain<AppContext>([
|
|
210
|
+
{
|
|
211
|
+
name: "detect-preview",
|
|
212
|
+
handle: (request, _event, context) => {
|
|
213
|
+
context.isPreview = request.nextUrl.searchParams.has("preview");
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
name: "preview-headers",
|
|
218
|
+
handle: (_request, _event, context) => {
|
|
219
|
+
if (!context.isPreview) return;
|
|
220
|
+
const response = NextResponse.next();
|
|
221
|
+
response.headers.set("cache-control", "no-store");
|
|
222
|
+
return response;
|
|
223
|
+
},
|
|
224
|
+
},
|
|
225
|
+
]);
|
|
149
226
|
```
|
|
150
227
|
|
|
151
|
-
|
|
228
|
+
Context is not forwarded downstream automatically. To make a request ID visible to route handlers, use Next.js's native request-header forwarding:
|
|
152
229
|
|
|
153
230
|
```ts
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
231
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
232
|
+
import { NextResponse } from "next/server";
|
|
233
|
+
|
|
234
|
+
export default chain([
|
|
235
|
+
{
|
|
236
|
+
name: "request-id",
|
|
237
|
+
handle: (request, _event, context) => {
|
|
238
|
+
const headers = new Headers(request.headers);
|
|
239
|
+
headers.set("x-request-id", context.requestId);
|
|
240
|
+
return NextResponse.next({
|
|
241
|
+
request: { headers },
|
|
242
|
+
});
|
|
243
|
+
},
|
|
244
|
+
},
|
|
245
|
+
]);
|
|
157
246
|
```
|
|
158
247
|
|
|
159
|
-
`
|
|
248
|
+
`NextResponse.next({ request: { headers } })` replaces the forwarded request-header set. Cloning `request.headers` preserves existing headers; omitted headers are removed downstream. This changes downstream request headers, not client-facing response headers. Validate client-controlled values and avoid forwarding sensitive headers without a reason. See [Security](docs/security.md#request-headers).
|
|
160
249
|
|
|
161
|
-
|
|
250
|
+
### Timeouts and error recovery
|
|
162
251
|
|
|
163
|
-
|
|
164
|
-
import { chain, defineHandler } from "@klnap/next-proxy-chain";
|
|
252
|
+
The chain-level `timeout` sets a deadline in milliseconds for each handler execution. Its default is `0`, which disables timeouts. A handler-level `timeout` overrides the chain default; handler value `0` disables that handler's deadline. The `when` predicate and `handle` share the same deadline.
|
|
165
253
|
|
|
166
|
-
|
|
254
|
+
```ts
|
|
255
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
167
256
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
257
|
+
import { loadRequestSettings } from "@/lib/proxy/settings";
|
|
258
|
+
|
|
259
|
+
export default chain(
|
|
260
|
+
[
|
|
261
|
+
{
|
|
262
|
+
name: "request-settings",
|
|
263
|
+
rules: { include: "/dashboard/**" },
|
|
264
|
+
timeout: 500,
|
|
265
|
+
handle: async (_request, _event, context) => {
|
|
266
|
+
const settings = await loadRequestSettings({ signal: context.signal });
|
|
267
|
+
if (settings.maintenanceMode) {
|
|
268
|
+
return new Response("Service unavailable", { status: 503 });
|
|
269
|
+
}
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
],
|
|
273
|
+
{
|
|
274
|
+
onError: () => new Response("Service unavailable", { status: 503 }),
|
|
175
275
|
},
|
|
176
|
-
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
export default chain([authHandler], { debug: "compact" });
|
|
276
|
+
);
|
|
180
277
|
```
|
|
181
278
|
|
|
182
|
-
|
|
279
|
+
Pass `context.signal` to work that supports cooperative cancellation. A timeout or request cancellation stops the chain from waiting, but cannot stop synchronous JavaScript or work that ignores its signal. `event.waitUntil()` work is outside the handler timeout.
|
|
183
280
|
|
|
184
|
-
|
|
281
|
+
For ordinary errors, handler-level `onError` takes precedence over chain-level `onError`. Returning `NextResponse.next()` or a successful `NextResponse.rewrite()` continues after the failed handler. A terminal `Response` stops the chain.
|
|
185
282
|
|
|
186
|
-
|
|
283
|
+
Timeout, request-cancellation, and engine-level recovery accept only a terminal Web `Response`; continuation and `NextResponse.rewrite()` are rejected. Without recovery, a timeout returns `500`. Cancellation stops this chain and returns a native `NextResponse.next()` handoff. Next.js may continue downstream routing, so cancellation is not a fail-closed response.
|
|
187
284
|
|
|
188
|
-
|
|
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
|
-
```
|
|
285
|
+
### Debugging and observability
|
|
197
286
|
|
|
198
|
-
|
|
199
|
-
proxy-chain GET /old-page 0.42ms
|
|
200
|
-
│ ↗ redirects redirect 0.14ms
|
|
201
|
-
│ destination: /new-page
|
|
202
|
-
└ REDIRECT 301 /new-page
|
|
203
|
-
```
|
|
287
|
+
Debugging defaults to `false`. Set `debug: true` as an alias for `"detailed"`, or choose a mode:
|
|
204
288
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
```
|
|
289
|
+
| Mode | Output |
|
|
290
|
+
| ---------- | ------------------------------------- |
|
|
291
|
+
| `compact` | Single-line request summary. |
|
|
292
|
+
| `detailed` | Request summary and handler outcomes. |
|
|
293
|
+
| `verbose` | Matching and execution details. |
|
|
211
294
|
|
|
212
|
-
|
|
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
|
-
```
|
|
295
|
+
These examples show a continuing security handler, a skipped authentication handler, and a staged localization rewrite. Request IDs and durations vary:
|
|
222
296
|
|
|
223
297
|
```text
|
|
224
|
-
proxy-chain GET /
|
|
225
|
-
│ ✓ security continue 0.11ms
|
|
226
|
-
│ ! analytics recovered 4.21ms
|
|
227
|
-
│ error policy: chain
|
|
228
|
-
│ ✓ intl continue 0.24ms
|
|
229
|
-
└ NEXT
|
|
298
|
+
[proxy-chain] req_d14c6cf2-962a-400a-8b7f-6e3c45545fc5 · GET /products · REWRITE /pl/products · 4.34ms · 3/3 handlers
|
|
230
299
|
```
|
|
231
300
|
|
|
232
|
-
Compact output is one line:
|
|
233
|
-
|
|
234
301
|
```text
|
|
235
|
-
proxy-chain GET /
|
|
302
|
+
[proxy-chain] GET /products
|
|
303
|
+
Request: req_63491ecd-a382-4cd4-9a88-b1e8575a33c5
|
|
304
|
+
│ ✓ security continue 0.15ms
|
|
305
|
+
│ ○ authentication skipped
|
|
306
|
+
│ ↪ localization rewrite 0.13ms
|
|
307
|
+
└ REWRITE /pl/products
|
|
308
|
+
Total: 0.80ms
|
|
236
309
|
```
|
|
237
310
|
|
|
238
|
-
|
|
311
|
+
The compact `reached/total` count includes skipped handlers. Handlers after a terminal outcome count only in the total. See the [diagnostics guide](docs/guides.md#diagnostics) for verbose output.
|
|
312
|
+
|
|
313
|
+
Use `onTrace` for structured diagnostics independently of formatted logging:
|
|
239
314
|
|
|
240
315
|
```ts
|
|
316
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
317
|
+
|
|
241
318
|
export default chain(handlers, {
|
|
242
|
-
|
|
319
|
+
debug: "detailed",
|
|
320
|
+
onTrace: (trace) => {
|
|
321
|
+
console.info({
|
|
322
|
+
requestId: trace.requestId,
|
|
323
|
+
outcome: trace.outcome.type,
|
|
324
|
+
handlers: trace.handlers,
|
|
325
|
+
});
|
|
326
|
+
},
|
|
243
327
|
});
|
|
244
328
|
```
|
|
245
329
|
|
|
246
|
-
|
|
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.
|
|
330
|
+
Formatted and structured traces omit header values, cookie values, raw query values, request bodies, application context values, and raw errors.
|
|
249
331
|
|
|
250
|
-
|
|
332
|
+
`tracePath: false` omits only the original request pathname from the top-level trace and formatted request line. Handler scope patterns and sanitized rewrite or redirect destination paths remain visible. Destination query values appear as `?[query]`.
|
|
251
333
|
|
|
252
|
-
|
|
334
|
+
## Configuration
|
|
253
335
|
|
|
254
|
-
|
|
336
|
+
`chain(entries, options?)` accepts native handlers and configured handler objects. Handler-level options are `rules`, `timeout`, `debug`, and `onError`.
|
|
255
337
|
|
|
256
|
-
|
|
338
|
+
| Chain option | Default | Description |
|
|
339
|
+
| --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------- |
|
|
340
|
+
| `timeout` | `0` | Per-handler deadline in milliseconds; `0` disables it. Handler values override the chain value. |
|
|
341
|
+
| `debug` | `false` | Formatted diagnostics. `true` means `"detailed"`; handlers can override the chain level. |
|
|
342
|
+
| `onError` | None | Recovery for ordinary handler errors; handler-level recovery takes precedence. |
|
|
343
|
+
| `onTrace` | None | Callback for structured request traces. |
|
|
344
|
+
| `tracePath` | `true` | Include the original pathname in diagnostics. |
|
|
345
|
+
| `logger` | Console logger (`info`) | Logger with `debug`, `info`, `warn`, and `error` methods. |
|
|
346
|
+
| `headerMergeStrategy` | `"last-write-wins"` | Resolve conflicts between response headers from continued handlers. |
|
|
347
|
+
| `cookieMergeStrategy` | `"last-write-wins"` | Resolve conflicts between cookie identities from continued handlers. |
|
|
348
|
+
| `strictOverrideCheck` | `false` | Throw at chain creation if native request-header override support cannot be verified. |
|
|
257
349
|
|
|
258
|
-
|
|
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 |
|
|
350
|
+
`onTrace`, `tracePath`, `logger`, merge strategies, and `strictOverrideCheck` are chain-level only. See the [API reference](docs/api.md#chain-options) for types and precedence.
|
|
267
351
|
|
|
268
|
-
|
|
352
|
+
## Compatibility
|
|
269
353
|
|
|
270
|
-
|
|
354
|
+
The package declares `next >=15.0.0` as a peer dependency and Node.js `>=20.0.0`. It provides ESM and CommonJS entrypoints with TypeScript declarations.
|
|
271
355
|
|
|
272
|
-
|
|
273
|
-
- `export default chain([...])` is the default export that Next.js expects. Put `export const config = { matcher }` next to it as usual.
|
|
274
|
-
- Handlers can be async.
|
|
275
|
-
- Handlers returned by other packages work unchanged, if they follow the native signature.
|
|
356
|
+
Packed consumer builds and live requests were verified with Next.js 15.5.29 and 16.3.2 on Node.js 26.13.1. This does not verify every version in the peer range. Next.js 15 Edge deployments have not been independently verified.
|
|
276
357
|
|
|
277
358
|
## Documentation
|
|
278
359
|
|
|
279
|
-
- [Concepts](
|
|
280
|
-
- [Guides](
|
|
281
|
-
- [API reference](
|
|
282
|
-
- [Security](
|
|
283
|
-
|
|
284
|
-
Runnable examples are in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/).
|
|
285
|
-
|
|
286
|
-
## Migration
|
|
287
|
-
|
|
288
|
-
Version 2 removes `proxyChain()`, `defineProxy()`, context-first handler signatures, and manually constructed rule objects. Upgrade with:
|
|
360
|
+
- [Concepts](docs/concepts.md) — execution model, matching, rewrites, HTTP composition, and context.
|
|
361
|
+
- [Guides](docs/guides.md) — practical integration examples, request IDs, cancellation, and diagnostics.
|
|
362
|
+
- [API reference](docs/api.md) — public exports, configuration, types, defaults, and precedence.
|
|
363
|
+
- [Security](docs/security.md) — trust boundaries, limitations, and safe integration.
|
|
289
364
|
|
|
290
|
-
|
|
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.
|
|
365
|
+
### AI coding agents
|
|
295
366
|
|
|
296
|
-
|
|
367
|
+
The package tarball includes version-matched consumer documentation and public declarations. Read [`llms.txt`](llms.txt) from the installed package at `node_modules/@klnap/next-proxy-chain/`.
|
|
297
368
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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.
|
|
303
|
-
- Framework-neutral use (Express, Hono) is not supported. The package depends on Next.js request and response semantics.
|
|
304
|
-
|
|
305
|
-
## Links
|
|
369
|
+
```text
|
|
370
|
+
Before integrating @klnap/next-proxy-chain, read the
|
|
371
|
+
installed package's llms.txt, README.md, relevant
|
|
372
|
+
documentation, and public TypeScript declarations.
|
|
306
373
|
|
|
307
|
-
|
|
308
|
-
|
|
374
|
+
Use the installed package's API as the source of truth.
|
|
375
|
+
```
|
|
309
376
|
|
|
310
377
|
## License
|
|
311
378
|
|
|
312
|
-
[MIT](
|
|
379
|
+
[MIT](LICENSE)
|