@klnap/next-proxy-chain 1.2.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 +18 -0
- package/README.md +277 -219
- package/dist/index.cjs +513 -440
- package/dist/index.d.cts +96 -189
- package/dist/index.d.ts +96 -189
- package/dist/index.js +512 -431
- 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 +19 -18
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
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
|
+
|
|
13
|
+
## 2.0.0
|
|
14
|
+
|
|
15
|
+
### Major Changes
|
|
16
|
+
|
|
17
|
+
- 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)`.
|
|
18
|
+
|
|
19
|
+
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.
|
|
20
|
+
|
|
3
21
|
## 1.2.0
|
|
4
22
|
|
|
5
23
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -2,320 +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
|
-
import { chain } from
|
|
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**
|
|
22
41
|
|
|
23
|
-
|
|
42
|
+
```bash
|
|
43
|
+
npm install @klnap/next-proxy-chain
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
24
47
|
|
|
25
|
-
|
|
48
|
+
### Getting started
|
|
26
49
|
|
|
27
50
|
```ts
|
|
28
|
-
import { chain } from
|
|
29
|
-
import { NextResponse } from
|
|
51
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
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
|
-
|
|
37
|
-
|
|
60
|
+
function redirectRoot(request: NextRequest) {
|
|
61
|
+
if (request.nextUrl.pathname === "/") {
|
|
62
|
+
return NextResponse.redirect(new URL("/home", request.url));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
38
65
|
|
|
39
|
-
|
|
66
|
+
export default chain([securityHeaders, redirectRoot]);
|
|
40
67
|
|
|
41
|
-
|
|
68
|
+
export const config = {
|
|
69
|
+
matcher: ["/:path*"],
|
|
70
|
+
};
|
|
71
|
+
```
|
|
42
72
|
|
|
43
|
-
|
|
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.
|
|
44
74
|
|
|
45
|
-
|
|
46
|
-
export default chain([
|
|
47
|
-
// Only /dashboard and its children.
|
|
48
|
-
[authProxy, '/dashboard/**'],
|
|
75
|
+
`securityHeaders` adds a response header. `redirectRoot` can stop the chain with a redirect. The chain keeps the earlier header on that redirect.
|
|
49
76
|
|
|
50
|
-
|
|
51
|
-
|
|
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. |
|
|
52
84
|
|
|
53
|
-
|
|
54
|
-
[privateProxy, { exclude: /^\/public(\/.*)?$/ }],
|
|
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.
|
|
55
86
|
|
|
56
|
-
|
|
57
|
-
[billingProxy, { include: { host: 'app.example.com', path: ['/billing/**', '/invoices/**'] } }],
|
|
58
|
-
])
|
|
59
|
-
```
|
|
87
|
+
### Conditional handlers
|
|
60
88
|
|
|
61
|
-
|
|
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.
|
|
62
90
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
91
|
+
```ts
|
|
92
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
93
|
+
import { NextResponse } from "next/server";
|
|
94
|
+
import { security, localization } from "@/lib/proxy/handlers";
|
|
67
95
|
|
|
68
|
-
|
|
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,
|
|
111
|
+
]);
|
|
112
|
+
```
|
|
69
113
|
|
|
70
|
-
|
|
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.
|
|
71
115
|
|
|
72
|
-
|
|
116
|
+
For example, this application-owned handler matches either billing path on the billing host, except the health route:
|
|
73
117
|
|
|
74
118
|
```ts
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
}
|
|
86
|
-
|
|
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))
|
|
91
|
-
return next()
|
|
92
|
-
})
|
|
93
|
-
|
|
94
|
-
export default chain([readSession, [requireUser, '/dashboard/**']])
|
|
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
|
+
}
|
|
95
130
|
```
|
|
96
131
|
|
|
97
|
-
|
|
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)`.
|
|
132
|
+
Matching controls routing, not authorization. Verify permissions in application-owned code, including at the data-access boundary.
|
|
101
133
|
|
|
102
|
-
###
|
|
134
|
+
### Reusable handlers
|
|
103
135
|
|
|
104
|
-
`
|
|
136
|
+
`defineHandler()` accepts the same configuration as an inline entry. Moving the object into `defineHandler()` does not change its options or implementation.
|
|
105
137
|
|
|
106
138
|
```ts
|
|
107
|
-
|
|
139
|
+
import { defineHandler } from "@klnap/next-proxy-chain";
|
|
140
|
+
import { NextResponse } from "next/server";
|
|
108
141
|
|
|
109
|
-
export
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
142
|
+
export const preview = defineHandler({
|
|
143
|
+
name: "preview",
|
|
144
|
+
rules: {
|
|
145
|
+
include: "/docs/**",
|
|
146
|
+
when: (request) => request.nextUrl.searchParams.has("preview"),
|
|
147
|
+
},
|
|
148
|
+
handle: () => {
|
|
149
|
+
const response = NextResponse.next();
|
|
150
|
+
response.headers.set("cache-control", "no-store");
|
|
151
|
+
return response;
|
|
152
|
+
},
|
|
153
|
+
});
|
|
114
154
|
```
|
|
115
155
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
## Continuing and stopping
|
|
156
|
+
Compose it like any other handler:
|
|
119
157
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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. |
|
|
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";
|
|
128
162
|
|
|
129
|
-
|
|
163
|
+
export default chain([security, preview, localization]);
|
|
164
|
+
```
|
|
130
165
|
|
|
131
|
-
|
|
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.
|
|
132
167
|
|
|
133
|
-
|
|
168
|
+
### Request context
|
|
134
169
|
|
|
135
|
-
|
|
170
|
+
The chain creates request metadata and a cancellation signal:
|
|
136
171
|
|
|
137
|
-
|
|
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. |
|
|
172
|
+
```ts
|
|
173
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
149
174
|
|
|
150
|
-
|
|
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
|
+
```
|
|
151
188
|
|
|
152
|
-
|
|
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. |
|
|
153
198
|
|
|
154
|
-
|
|
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.
|
|
155
200
|
|
|
156
201
|
```ts
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
+
]);
|
|
160
226
|
```
|
|
161
227
|
|
|
162
|
-
|
|
228
|
+
Context is not forwarded downstream automatically. To make a request ID visible to route handlers, use Next.js's native request-header forwarding:
|
|
163
229
|
|
|
164
230
|
```ts
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
})
|
|
168
|
-
```
|
|
231
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
232
|
+
import { NextResponse } from "next/server";
|
|
169
233
|
|
|
170
|
-
|
|
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
|
+
]);
|
|
246
|
+
```
|
|
171
247
|
|
|
172
|
-
|
|
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).
|
|
173
249
|
|
|
174
|
-
|
|
175
|
-
import { chain, defineHandler } from '@klnap/next-proxy-chain'
|
|
250
|
+
### Timeouts and error recovery
|
|
176
251
|
|
|
177
|
-
|
|
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.
|
|
178
253
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
254
|
+
```ts
|
|
255
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
256
|
+
|
|
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 }),
|
|
186
275
|
},
|
|
187
|
-
|
|
188
|
-
})
|
|
189
|
-
|
|
190
|
-
export default chain([authHandler], { debug: 'compact' })
|
|
276
|
+
);
|
|
191
277
|
```
|
|
192
278
|
|
|
193
|
-
|
|
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.
|
|
194
280
|
|
|
195
|
-
|
|
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.
|
|
196
282
|
|
|
197
|
-
|
|
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.
|
|
198
284
|
|
|
199
|
-
|
|
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
|
-
```
|
|
285
|
+
### Debugging and observability
|
|
208
286
|
|
|
209
|
-
|
|
210
|
-
proxy-chain GET /old-page 0.42ms
|
|
211
|
-
│ ↗ redirects redirect 0.14ms
|
|
212
|
-
│ destination: /new-page
|
|
213
|
-
└ REDIRECT 301 /new-page
|
|
214
|
-
```
|
|
287
|
+
Debugging defaults to `false`. Set `debug: true` as an alias for `"detailed"`, or choose a mode:
|
|
215
288
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
```
|
|
289
|
+
| Mode | Output |
|
|
290
|
+
| ---------- | ------------------------------------- |
|
|
291
|
+
| `compact` | Single-line request summary. |
|
|
292
|
+
| `detailed` | Request summary and handler outcomes. |
|
|
293
|
+
| `verbose` | Matching and execution details. |
|
|
222
294
|
|
|
223
|
-
|
|
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
|
-
```
|
|
295
|
+
These examples show a continuing security handler, a skipped authentication handler, and a staged localization rewrite. Request IDs and durations vary:
|
|
233
296
|
|
|
234
297
|
```text
|
|
235
|
-
proxy-chain GET /
|
|
236
|
-
│ ✓ security continue 0.11ms
|
|
237
|
-
│ ! analytics recovered 4.21ms
|
|
238
|
-
│ error policy: chain
|
|
239
|
-
│ ✓ intl continue 0.24ms
|
|
240
|
-
└ NEXT
|
|
298
|
+
[proxy-chain] req_d14c6cf2-962a-400a-8b7f-6e3c45545fc5 · GET /products · REWRITE /pl/products · 4.34ms · 3/3 handlers
|
|
241
299
|
```
|
|
242
300
|
|
|
243
|
-
Compact output is one line:
|
|
244
|
-
|
|
245
301
|
```text
|
|
246
|
-
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
|
|
247
309
|
```
|
|
248
310
|
|
|
249
|
-
|
|
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:
|
|
250
314
|
|
|
251
315
|
```ts
|
|
316
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
317
|
+
|
|
252
318
|
export default chain(handlers, {
|
|
253
|
-
|
|
254
|
-
|
|
319
|
+
debug: "detailed",
|
|
320
|
+
onTrace: (trace) => {
|
|
321
|
+
console.info({
|
|
322
|
+
requestId: trace.requestId,
|
|
323
|
+
outcome: trace.outcome.type,
|
|
324
|
+
handlers: trace.handlers,
|
|
325
|
+
});
|
|
326
|
+
},
|
|
327
|
+
});
|
|
255
328
|
```
|
|
256
329
|
|
|
257
|
-
|
|
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.
|
|
330
|
+
Formatted and structured traces omit header values, cookie values, raw query values, request bodies, application context values, and raw errors.
|
|
262
331
|
|
|
263
|
-
|
|
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]`.
|
|
264
333
|
|
|
265
|
-
|
|
334
|
+
## Configuration
|
|
266
335
|
|
|
267
|
-
|
|
336
|
+
`chain(entries, options?)` accepts native handlers and configured handler objects. Handler-level options are `rules`, `timeout`, `debug`, and `onError`.
|
|
268
337
|
|
|
269
|
-
|
|
|
270
|
-
|
|
|
271
|
-
|
|
|
272
|
-
|
|
|
273
|
-
|
|
|
274
|
-
|
|
|
275
|
-
|
|
|
276
|
-
|
|
|
277
|
-
|
|
|
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. |
|
|
278
349
|
|
|
279
|
-
|
|
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.
|
|
280
351
|
|
|
281
|
-
##
|
|
352
|
+
## Compatibility
|
|
282
353
|
|
|
283
|
-
|
|
284
|
-
- `export default chain([...])` is the default export that Next.js expects. Put `export const config = { matcher }` next to it as usual.
|
|
285
|
-
- Handlers can be async.
|
|
286
|
-
- Handlers returned by other packages work unchanged, if they follow the native signature.
|
|
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.
|
|
287
355
|
|
|
288
|
-
|
|
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.
|
|
289
357
|
|
|
290
358
|
## Documentation
|
|
291
359
|
|
|
292
|
-
- [Concepts](
|
|
293
|
-
- [Guides](
|
|
294
|
-
- [API reference](
|
|
295
|
-
- [Security](
|
|
296
|
-
|
|
297
|
-
Runnable examples are in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/).
|
|
298
|
-
|
|
299
|
-
## Migration
|
|
300
|
-
|
|
301
|
-
No change is required. `proxyChain()` and `defineProxy()` keep working. To move to `chain()`:
|
|
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.
|
|
302
364
|
|
|
303
|
-
|
|
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.
|
|
365
|
+
### AI coding agents
|
|
306
366
|
|
|
307
|
-
|
|
308
|
-
|
|
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.
|
|
310
|
-
- Node.js `>=20`, Bun `>=1`.
|
|
311
|
-
- 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
|
-
- Framework-neutral use (Express, Hono) is not supported. The package depends on Next.js request and response semantics.
|
|
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/`.
|
|
313
368
|
|
|
314
|
-
|
|
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.
|
|
315
373
|
|
|
316
|
-
|
|
317
|
-
|
|
374
|
+
Use the installed package's API as the source of truth.
|
|
375
|
+
```
|
|
318
376
|
|
|
319
377
|
## License
|
|
320
378
|
|
|
321
|
-
[MIT](
|
|
379
|
+
[MIT](LICENSE)
|