@klnap/next-proxy-chain 1.0.6 → 1.1.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
@@ -4,6 +4,38 @@ All notable changes to `@klnap/next-proxy-chain` will be documented in this file
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [1.1.0] - 2026-11-22
8
+
9
+ ### Added
10
+
11
+ - `chain(entries, options?)`: the recommended entry point. Plain functions receive the native `(request, event)` arguments. `defineProxy()` rules receive `(request, context, event)`.
12
+ - Scoped tuples: `[handler, scope]`, where `scope` is a path string, an array, a RegExp, or an object `{ include?, exclude? }`. Include objects accept `host`.
13
+ - Exported types `ChainEntry`, `ChainScope`, and `NativeProxy`.
14
+ - `chain()` passes the request context to plain handlers as an optional third argument: `(request, event, context)`.
15
+
16
+ ### Deprecated
17
+
18
+ - `proxyChain()` is deprecated in favor of `chain()`. It keeps its behavior. Its removal would be a major release.
19
+
20
+ ### Fixed
21
+
22
+ - A native Next.js handler passed to `proxyChain()` received the context instead of `event`, so `event.waitUntil()` failed and the request returned `500`. `chain()` avoids this. `proxyChain()` keeps its signature.
23
+
24
+ ### Documentation
25
+
26
+ - README rewritten to start with `chain()`. Advanced features follow in separate sections.
27
+ - `docs/api.md` and `docs/concepts.md` describe native handlers and context rules.
28
+
29
+ ## [1.0.7] - 2026-11-22
30
+
31
+ ### Fixed
32
+
33
+ - Responses with immutable headers (`Response.redirect()`, `fetch()` responses) are copied before headers are merged. Before, a rule returning them produced a `500` on Node.js.
34
+ - A fail-closed `500` keeps the headers and cookies that earlier rules set, such as a CSP header.
35
+ - Request overrides go to Next.js only when a rule changed a request header. Before, every request header was encoded as `x-middleware-request-*` on every request.
36
+ - `hostFolderHeader` matches whole path segments: `/tenant-other` is not treated as inside `/tenant`.
37
+ - `strictOverrideCheck` verifies that Next.js applies request overrides, not only the continuation flag.
38
+
7
39
  ## [1.0.6] - 2026-11-22
8
40
 
9
41
  ### Fixed
package/README.md CHANGED
@@ -1,32 +1,20 @@
1
1
  # @klnap/next-proxy-chain
2
2
 
3
- Compose independent request rules for Next.js `proxy.ts` (or `middleware.ts`) without writing one long function.
3
+ Run several Next.js `proxy.ts` (or `middleware.ts`) handlers as one chain. Each handler can be a plain native Next.js function, scoped to certain paths, and the chain stops or continues according to what each handler returns.
4
4
 
5
- Next.js gives each app one `proxy` export. Once that file also checks sessions, sets security headers, picks a locale, and redirects old URLs, the order of those checks matters, and each one has to know about the others. This package lets each concern be its own rule. The rules run in order, can be limited to certain paths or hosts, and share request-scoped state without any global variables.
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.
6
6
 
7
7
  ```ts
8
- import { defineProxy, next, path, proxyChain } from '@klnap/next-proxy-chain'
9
- import { NextResponse } from 'next/server'
10
-
11
- const securityHeaders = defineProxy('security-headers', () =>
12
- next({ headers: { 'x-frame-options': 'DENY' } })
13
- )
14
-
15
- const requireSession = defineProxy('require-session', (req) => {
16
- if (!req.cookies.has('session')) {
17
- return NextResponse.redirect(new URL('/login', req.url))
18
- }
19
- return next()
20
- })
21
-
22
- export default proxyChain([securityHeaders, requireSession({ include: path('/dashboard/**') })])
8
+ import { chain } from '@klnap/next-proxy-chain'
23
9
 
24
- export const config = {
25
- matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
26
- }
10
+ export default chain([
11
+ intlProxy,
12
+ [authProxy, '/dashboard/**'],
13
+ securityProxy,
14
+ ])
27
15
  ```
28
16
 
29
- This sets `X-Frame-Options` on every response and sends visitors without a session cookie from `/dashboard` to `/login`. The security header comes first, so it also appears on the redirect.
17
+ `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.
30
18
 
31
19
  ## Install
32
20
 
@@ -38,44 +26,148 @@ bun add @klnap/next-proxy-chain
38
26
 
39
27
  `next` is a peer dependency (`>=15.0.0`). The package has no runtime dependencies.
40
28
 
41
- ## When to use it
29
+ ## Basic composition
30
+
31
+ Pass handlers in the order they should run. Each one receives the native `(request, event)` arguments, so `event.waitUntil()` works.
32
+
33
+ ```ts
34
+ import { chain } from '@klnap/next-proxy-chain'
35
+ import { NextResponse } from 'next/server'
36
+
37
+ function analytics(request, event) {
38
+ event.waitUntil(sendPageView(request.nextUrl.pathname))
39
+ return NextResponse.next()
40
+ }
41
+
42
+ export default chain([analytics, intlProxy, securityProxy])
43
+ ```
42
44
 
43
- Use it when one Proxy file needs several independent concerns, for example:
45
+ 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.
44
46
 
45
- - a session check on some routes and not others,
46
- - security headers on every response,
47
- - a locale rewrite,
48
- - a redirect from old URLs,
49
- - request IDs passed to route handlers.
47
+ ## Scoped handlers
50
48
 
51
- A single redirect rule does not need it. Write `NextResponse.redirect` directly in `proxy.ts`.
49
+ Wrap a handler in a tuple to run it only for some paths or hosts:
52
50
 
53
- It is a composition layer, not a security product. It does not authenticate users, verify tokens, or replace Next.js routing. It runs the rules you write, in the order you list them.
51
+ ```ts
52
+ export default chain([
53
+ // Only /dashboard and its children.
54
+ [authProxy, '/dashboard/**'],
54
55
 
55
- ## How it works
56
+ // Everything except /login.
57
+ [adminProxy, { exclude: '/admin/login' }],
58
+
59
+ // RegExp works too.
60
+ [privateProxy, { exclude: /^\/public(\/.*)?$/ }],
61
+
62
+ // Several patterns and a host.
63
+ [billingProxy, { include: { host: 'app.example.com', path: ['/billing/**', '/invoices/**'] } }],
64
+ ])
65
+ ```
56
66
 
57
- - Rules run in array order. A rule continues by returning `next()` or nothing, and stops the chain by returning a `Response`.
58
- - A rule can be scoped with `include` and `exclude` paths or hosts. Rules that do not match are skipped.
59
- - Headers and cookies set by earlier rules are kept on the final response, unless a later rule overrides them.
60
- - Each request gets its own context. Rules can share values through it without globals.
61
- - Errors and timeouts can be recovered with `onError`. By default they produce a 500.
67
+ Path patterns:
68
+
69
+ - `*` matches one segment: `/api/*` matches `/api/users`, not `/api/users/123`.
70
+ - `**` matches any depth, including zero segments: `/docs/**` matches `/docs` and `/docs/a/b`.
71
+ - `:name` matches one segment and does not capture a value.
72
+ - A RegExp is matched against the decoded path. Anchor it with `^` and `$` for an exact match.
73
+
74
+ 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
+
76
+ ## Context and typed rules
77
+
78
+ A handler that needs per-request state is written with `defineProxy()`. It receives a context object as its second argument:
79
+
80
+ ```ts
81
+ import { chain, defineProxy, next } from '@klnap/next-proxy-chain'
62
82
 
63
- [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md) explains the execution model in full.
83
+ type Session = { user?: string }
84
+
85
+ const readSession = defineProxy<Session>('read-session', (request, session) => {
86
+ session.user = request.cookies.get('user')?.value
87
+ return next()
88
+ })
89
+
90
+ const requireUser = defineProxy<Session>('require-user', (request, session) => {
91
+ if (!session.user) return NextResponse.redirect(new URL('/login', request.url))
92
+ return next()
93
+ })
94
+
95
+ export default chain(
96
+ [readSession, [requireUser, '/dashboard/**']],
97
+ { createContext: (): Session => ({}) }
98
+ )
99
+ ```
100
+
101
+ - The context is created for each request and is not shared between requests.
102
+ - `createContext` is required when a rule declares a context type. Passing a rule that expects a different type is a compile-time error.
103
+ - Rules run in array order. Put the rule that sets a value before the rule that reads it.
104
+
105
+ Use `defineProxy()` only when you need the context or a named rule. A plain function is enough for everything else.
106
+
107
+ ## Continuing and stopping
108
+
109
+ | A handler returns | Effect |
110
+ | :--- | :--- |
111
+ | `undefined` or nothing | Continue. |
112
+ | `NextResponse.next()` | Continue. Its request-header overrides are kept. |
113
+ | `NextResponse.rewrite(url)` | Continue. The rewrite is applied at the end unless a later handler stops. |
114
+ | `NextResponse.redirect(url)`, `NextResponse.json()`, `Response`, `Response.redirect()` | Stop and return that response. |
115
+ | `next({ request, headers })` | Continue, and apply the given headers. This is a library token; plain Next.js handlers should return `NextResponse.next()`. |
116
+ | A thrown error or a rejected promise | Fail closed with `500`, unless `onError` is set. |
117
+
118
+ Stopping is immediate. A handler after a stopping handler does not run, so put checks that must always run before any handler that might answer the request.
119
+
120
+ Headers and cookies that earlier handlers set are kept on the response that stops the chain. Handlers after it do not contribute.
121
+
122
+ ## Options
123
+
124
+ `chain(entries, options)` accepts the same options as `proxyChain`:
125
+
126
+ | Option | Purpose |
127
+ | :--- | :--- |
128
+ | `createContext` | Creates the context for each request. Required for typed rules. |
129
+ | `onError` | Returns a `Response` to stop with, `next()` to continue, or nothing for a `500`. |
130
+ | `ruleTimeoutMs` | Time limit per handler. `0` (default) disables it. |
131
+ | `headerMergeStrategy`, `cookieMergeStrategy` | How conflicting response headers and cookies are resolved. |
132
+ | `requestHeaderPolicy` | Which request headers `next({ request })` may set. |
133
+ | `debug`, `logger` | One log line per handler, and a custom logger. |
134
+ | `strictOverrideCheck` | Throw at startup if Next.js does not apply request overrides. |
135
+ | `hostFolderHeader` | Opt-in multi-tenant folder prefix for rewrites. |
136
+
137
+ The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
138
+
139
+ ## Native compatibility
140
+
141
+ - A plain handler gets `(request, event)`, exactly as in a native `proxy.ts`. `chain()` also passes the request context as an optional third argument, which Next.js never uses.
142
+ - `export default chain([...])` is the default export that Next.js expects. Put `export const config = { matcher }` next to it as usual.
143
+ - Handlers can be async.
144
+ - Handlers returned by other packages work unchanged, if they follow the native signature.
145
+
146
+ `proxyChain()` is a deprecated alias that is still exported and unchanged. Its plain functions receive `(request, context, event)`. Use `chain()` in new code.
64
147
 
65
148
  ## Documentation
66
149
 
67
- - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): rule order, continuation, scoping, headers, cookies, errors.
68
- - [Guides](https://github.com/klnap/next-proxy-chain/blob/main/docs/guides.md): recipes for common tasks, with links to runnable examples.
150
+ - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): execution order, continuation, scoping, headers, cookies, errors.
151
+ - [Guides](https://github.com/klnap/next-proxy-chain/blob/main/docs/guides.md): recipes for common tasks.
69
152
  - [API reference](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md): every export and option.
70
153
  - [Security](https://github.com/klnap/next-proxy-chain/blob/main/docs/security.md): trust boundaries and safe usage.
71
154
 
72
- Runnable examples live in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/). They are type-checked and tested in this repository.
155
+ Runnable examples are in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/).
156
+
157
+ ## Migration
158
+
159
+ No change is required. `proxyChain()` and `defineProxy()` keep working. To move to `chain()`:
160
+
161
+ 1. Replace `proxyChain(entries)` with `chain(entries)`.
162
+ 2. Plain functions that used the old `(request, context, event)` signature: rewrite them with `defineProxy()`, which keeps that signature.
163
+ 3. Replace `path()` and `host()` helpers with strings, arrays, or objects where you like. They still work.
73
164
 
74
165
  ## Compatibility
75
166
 
76
- - Next.js: peer `>=15.0.0`. The test suite runs against Next.js 16.3.2. Next.js 15 `middleware.ts` is covered by integration tests that model its behavior, not by a Next.js 15 application.
167
+ - 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.
77
168
  - Node.js `>=20`, Bun `>=1`.
78
- - Next.js 16 runs `proxy.ts` on the Node.js runtime by default. The package uses only Web platform APIs (`Headers`, `Request`, `Response`, `URL`), so it should also work on the Edge runtime, but that is not tested here.
169
+ - 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.
170
+ - Framework-neutral use (Express, Hono) is not supported. The package depends on Next.js request and response semantics.
79
171
 
80
172
  ## Links
81
173
 
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  RuleTimeoutError: () => RuleTimeoutError,
24
+ chain: () => chain,
24
25
  createProxyContext: () => createProxyContext,
25
26
  defineProxy: () => defineProxy,
26
27
  host: () => host,
@@ -53,6 +54,7 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
53
54
  "x-middleware-next",
54
55
  "x-middleware-override-headers"
55
56
  ]);
57
+ var CONTEXT_RULE = /* @__PURE__ */ Symbol.for("proxy-chain.context-rule");
56
58
 
57
59
  // src/core/actions.ts
58
60
  function next(options = {}) {
@@ -62,14 +64,14 @@ function isNextResult(value) {
62
64
  return typeof value === "object" && value !== null && NEXT in value;
63
65
  }
64
66
 
67
+ // src/core/engine.ts
68
+ var import_server2 = require("next/server");
69
+
65
70
  // src/core/context.ts
66
71
  function createProxyContext() {
67
72
  return /* @__PURE__ */ new Map();
68
73
  }
69
74
 
70
- // src/core/engine.ts
71
- var import_server2 = require("next/server");
72
-
73
75
  // src/core/headers.ts
74
76
  function normalizeHeaderName(name) {
75
77
  return name.toLowerCase();
@@ -216,16 +218,20 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
216
218
  function physicalFolderPrefix(raw) {
217
219
  return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
218
220
  }
221
+ function isInsideFolder(pathname, folder) {
222
+ if (folder === "/") return true;
223
+ return pathname === folder || pathname.startsWith(`${folder}/`);
224
+ }
219
225
  function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
220
226
  try {
221
227
  const parsed = new URL(rewriteUrl, baseUrl);
222
- if (!parsed.pathname.startsWith(folder)) {
228
+ if (!isInsideFolder(parsed.pathname, folder)) {
223
229
  parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
224
230
  return parsed.toString();
225
231
  }
226
232
  return rewriteUrl;
227
233
  } catch {
228
- if (!rewriteUrl.startsWith(folder)) {
234
+ if (!isInsideFolder(rewriteUrl, folder)) {
229
235
  return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
230
236
  }
231
237
  return rewriteUrl;
@@ -490,7 +496,8 @@ function runOverrideProbe() {
490
496
  const testRes = import_server.NextResponse.next({
491
497
  request: { headers: new Headers({ "x-proxy-chain-probe": "1" }) }
492
498
  });
493
- return testRes.headers.get("x-middleware-next") === "1";
499
+ const overridden = (testRes.headers.get("x-middleware-override-headers") ?? "").split(",").map((name) => name.trim());
500
+ return testRes.headers.get("x-middleware-next") === "1" && overridden.includes("x-proxy-chain-probe") && testRes.headers.get("x-middleware-request-x-proxy-chain-probe") === "1";
494
501
  }
495
502
  function throwForCachedProbe(probe) {
496
503
  if (probe.kind === "unsupported") throw new Error(UNSUPPORTED_OVERRIDE_MSG);
@@ -600,8 +607,19 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
600
607
  for (const key of seenHeaders) {
601
608
  if (!headers.has(key)) dropHeaders.push(key);
602
609
  }
603
- applyMergedToResponse(res, headers, cookies, dropHeaders);
604
- return res;
610
+ try {
611
+ applyMergedToResponse(res, headers, cookies, dropHeaders);
612
+ return res;
613
+ } catch (err) {
614
+ if (!(err instanceof TypeError)) throw err;
615
+ const copy = new Response(res.body, {
616
+ status: res.status,
617
+ statusText: res.statusText,
618
+ headers: new Headers(res.headers)
619
+ });
620
+ applyMergedToResponse(copy, headers, cookies, dropHeaders);
621
+ return copy;
622
+ }
605
623
  }
606
624
 
607
625
  // src/core/timeout.ts
@@ -672,6 +690,7 @@ function defineProxy(nameOrRun, maybeRun) {
672
690
  value: defaultName ?? "",
673
691
  configurable: true
674
692
  });
693
+ Object.defineProperty(proxy, CONTEXT_RULE, { value: true });
675
694
  return proxy;
676
695
  }
677
696
  function resolveConfig(overrides, fallbackCreateContext) {
@@ -728,6 +747,15 @@ function proxyChain(optionsOrEntries, maybeEntries) {
728
747
  let pendingRewriteUrl = null;
729
748
  const headerWrites = [];
730
749
  const cookieWrites = [];
750
+ const failClosed = () => finalizeResponse(
751
+ safeInternalError(),
752
+ headerWrites,
753
+ cookieWrites,
754
+ headerMergeStrategy,
755
+ cookieMergeStrategy,
756
+ logger,
757
+ debug
758
+ );
731
759
  const materializeRequest = () => {
732
760
  if (!pendingRequestOverrides) return currentReq;
733
761
  if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
@@ -754,13 +782,13 @@ function proxyChain(optionsOrEntries, maybeEntries) {
754
782
  const recoverRuleError = async (err, i, label, req2, startedAt) => {
755
783
  if (!config.onError) {
756
784
  logger.error({ rule: label, err }, "rule threw");
757
- return { response: safeInternalError() };
785
+ return { response: failClosed() };
758
786
  }
759
787
  try {
760
788
  const recovered = await config.onError(err, i, req2, ctx);
761
- if (recovered == null) return { response: safeInternalError() };
789
+ if (recovered == null) return { response: failClosed() };
762
790
  if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
763
- if (!(recovered instanceof Response)) return { response: safeInternalError() };
791
+ if (!(recovered instanceof Response)) return { response: failClosed() };
764
792
  stripRoutingOverrides(recovered);
765
793
  headerWrites.push({
766
794
  ruleIndex: i,
@@ -800,7 +828,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
800
828
  };
801
829
  } catch (onErrorErr) {
802
830
  logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
803
- return { response: safeInternalError() };
831
+ return { response: failClosed() };
804
832
  }
805
833
  };
806
834
  try {
@@ -928,19 +956,20 @@ function proxyChain(optionsOrEntries, maybeEntries) {
928
956
  finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
929
957
  } else {
930
958
  const currentPath = finalReq.nextUrl.pathname;
931
- if (!currentPath.startsWith(cleanFolder)) {
959
+ if (!isInsideFolder(currentPath, cleanFolder)) {
932
960
  const targetUrl = finalReq.nextUrl.clone();
933
961
  targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
934
962
  finalRewriteUrl = targetUrl.toString();
935
963
  }
936
964
  }
937
965
  }
966
+ const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
938
967
  let final;
939
968
  if (finalRewriteUrl) {
940
969
  const rewriteTarget = new URL(finalRewriteUrl, finalReq.url);
941
- final = import_server2.NextResponse.rewrite(rewriteTarget, { request: { headers: finalReq.headers } });
970
+ final = import_server2.NextResponse.rewrite(rewriteTarget, requestInit);
942
971
  } else {
943
- final = import_server2.NextResponse.next({ request: { headers: finalReq.headers } });
972
+ final = import_server2.NextResponse.next(requestInit);
944
973
  }
945
974
  return finalizeResponse(
946
975
  final,
@@ -971,13 +1000,46 @@ function proxyChain(optionsOrEntries, maybeEntries) {
971
1000
  } catch {
972
1001
  }
973
1002
  }
974
- return safeInternalError();
1003
+ return failClosed();
975
1004
  }
976
1005
  };
977
1006
  }
1007
+
1008
+ // src/core/chain.ts
1009
+ function isContextRule(value) {
1010
+ return typeof value === "function" && value[CONTEXT_RULE] === true;
1011
+ }
1012
+ function isScopeObject2(value) {
1013
+ return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
1014
+ }
1015
+ function toFilter(scope) {
1016
+ if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
1017
+ return { include: scope };
1018
+ }
1019
+ function fromNative(handler) {
1020
+ const run = (req, ctx, event) => handler(req, event, ctx);
1021
+ const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
1022
+ return { run, name };
1023
+ }
1024
+ function toEntry(entry) {
1025
+ if (Array.isArray(entry)) {
1026
+ const [target, scope] = entry;
1027
+ const filter = toFilter(scope);
1028
+ if (isContextRule(target)) return target(filter);
1029
+ return withPaths(fromNative(target), filter);
1030
+ }
1031
+ if (isContextRule(entry)) return entry;
1032
+ if (typeof entry === "function") return fromNative(entry);
1033
+ return entry;
1034
+ }
1035
+ function chain(entries, options) {
1036
+ const normalized = entries.map((entry) => toEntry(entry));
1037
+ return proxyChain(options ?? {}, normalized);
1038
+ }
978
1039
  // Annotate the CommonJS export names for ESM import in node:
979
1040
  0 && (module.exports = {
980
1041
  RuleTimeoutError,
1042
+ chain,
981
1043
  createProxyContext,
982
1044
  defineProxy,
983
1045
  host,
package/dist/index.d.cts CHANGED
@@ -54,12 +54,27 @@ type ProxyPathFilter = {
54
54
  exclude?: RouteScopeList;
55
55
  name?: string;
56
56
  };
57
+ /**
58
+ * Type-only brand carried by defineProxy() rules. It records the context type a rule expects.
59
+ * Chain entries match on it as an object, which keeps handler parameters contextually typed.
60
+ */
61
+ declare const CONTEXT_BRAND: unique symbol;
62
+ /** Entry type for a defineProxy() rule that expects context TContext. */
63
+ type ContextRuleEntry<TContext = ProxyContext> = {
64
+ readonly [CONTEXT_BRAND]: TContext;
65
+ };
66
+ /**
67
+ * A native Next.js proxy handler: `(request, event)`. Use it in chain() without any wrapper.
68
+ */
69
+ type NativeProxy<TContext = ProxyContext> = (req: NextRequest, event: NextFetchEvent,
70
+ /** Request context from createContext. Next.js never passes it; chain() does, as the third argument. */
71
+ context: TContext) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
57
72
  /**
58
73
  * A single proxy execution function.
59
74
  */
60
75
  type ProxyFn<TContext = ProxyContext> = (req: NextRequest, ctx: TContext, event: NextFetchEvent) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
61
76
  type ProxyRule<TContext = ProxyContext> = BaseProxyRule<ProxyFn<TContext>>;
62
- type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>);
77
+ type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>) & ContextRuleEntry<TContext>;
63
78
  type Entry<TContext = ProxyContext> = ProxyFn<TContext> | ProxyRule<TContext>;
64
79
  type MergeStrategy = 'last-write-wins' | 'first-write-wins' | ((key: string, existing: string, incoming: string) => string | null);
65
80
  interface ChainLogger {
@@ -126,12 +141,6 @@ declare function next(options?: NextOptions): NextResult;
126
141
  */
127
142
  declare function isNextResult(value: unknown): value is NextResult;
128
143
 
129
- /**
130
- * Creates an isolated per-request context instance.
131
- * Backed by Map to eliminate prototype pollution risks.
132
- */
133
- declare function createProxyContext(): ProxyContext;
134
-
135
144
  /**
136
145
  * Creates a reusable, scope-aware proxy rule function.
137
146
  *
@@ -154,12 +163,38 @@ type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<NextRes
154
163
  * i18nRule,
155
164
  * ])
156
165
  */
166
+ /** @deprecated Use chain(). Plain functions here receive (request, context, event). */
157
167
  declare function proxyChain(entries: Entry<ProxyContext>[]): ProxyHandler;
158
168
  declare function proxyChain(options: ProxyChainOptions<ProxyContext>, entries: Entry<ProxyContext>[]): ProxyHandler;
159
169
  declare function proxyChain<TContext>(options: ProxyChainOptions<TContext> & {
160
170
  createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
161
171
  }, entries: Entry<TContext>[]): ProxyHandler;
162
172
 
173
+ /** Scope for a tuple entry: `[handler, scope]`. A string, RegExp, or array is shorthand for `include`. */
174
+ type ChainScope = Omit<ProxyPathFilter, 'name'> | PathMatcher | readonly PathMatcher[];
175
+ /** One entry of chain(): a native handler, a defineProxy() rule, a rule object, or a scoped tuple. */
176
+ type ChainEntry<TContext = ProxyContext> = NativeProxy<TContext> | ContextRuleEntry<TContext> | ProxyRule<TContext> | readonly [NativeProxy<TContext> | ContextRuleEntry<TContext>, ChainScope];
177
+ /**
178
+ * Composes native Next.js proxy handlers and optional rules into one proxy.
179
+ *
180
+ * - A plain function receives `(request, event)`, exactly like a native `proxy.ts` export.
181
+ * - A `defineProxy()` rule receives `(request, context, event)`.
182
+ * - `[handler, scope]` runs the handler only for matching paths or hosts.
183
+ *
184
+ * @example
185
+ * export default chain([intlProxy, [authProxy, { include: '/dashboard/**' }]])
186
+ */
187
+ declare function chain(entries: readonly ChainEntry<ProxyContext>[], options?: ProxyChainOptions<ProxyContext>): ReturnType<typeof proxyChain>;
188
+ declare function chain<TContext>(entries: readonly ChainEntry<TContext>[], options: ProxyChainOptions<TContext> & {
189
+ createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
190
+ }): ReturnType<typeof proxyChain>;
191
+
192
+ /**
193
+ * Creates an isolated per-request context instance.
194
+ * Backed by Map to eliminate prototype pollution risks.
195
+ */
196
+ declare function createProxyContext(): ProxyContext;
197
+
163
198
  /**
164
199
  * Builds a compiled Host matcher RegExp from domain names, `*.example.com` wildcards, or regex patterns.
165
200
  */
@@ -178,4 +213,4 @@ declare class RuleTimeoutError extends Error {
178
213
  constructor(ruleName: string, timeoutMs: number);
179
214
  }
180
215
 
181
- export { type ChainLogger, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
216
+ export { type ChainEntry, type ChainLogger, type ChainScope, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NativeProxy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, chain, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
package/dist/index.d.ts CHANGED
@@ -54,12 +54,27 @@ type ProxyPathFilter = {
54
54
  exclude?: RouteScopeList;
55
55
  name?: string;
56
56
  };
57
+ /**
58
+ * Type-only brand carried by defineProxy() rules. It records the context type a rule expects.
59
+ * Chain entries match on it as an object, which keeps handler parameters contextually typed.
60
+ */
61
+ declare const CONTEXT_BRAND: unique symbol;
62
+ /** Entry type for a defineProxy() rule that expects context TContext. */
63
+ type ContextRuleEntry<TContext = ProxyContext> = {
64
+ readonly [CONTEXT_BRAND]: TContext;
65
+ };
66
+ /**
67
+ * A native Next.js proxy handler: `(request, event)`. Use it in chain() without any wrapper.
68
+ */
69
+ type NativeProxy<TContext = ProxyContext> = (req: NextRequest, event: NextFetchEvent,
70
+ /** Request context from createContext. Next.js never passes it; chain() does, as the third argument. */
71
+ context: TContext) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
57
72
  /**
58
73
  * A single proxy execution function.
59
74
  */
60
75
  type ProxyFn<TContext = ProxyContext> = (req: NextRequest, ctx: TContext, event: NextFetchEvent) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
61
76
  type ProxyRule<TContext = ProxyContext> = BaseProxyRule<ProxyFn<TContext>>;
62
- type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>);
77
+ type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>) & ContextRuleEntry<TContext>;
63
78
  type Entry<TContext = ProxyContext> = ProxyFn<TContext> | ProxyRule<TContext>;
64
79
  type MergeStrategy = 'last-write-wins' | 'first-write-wins' | ((key: string, existing: string, incoming: string) => string | null);
65
80
  interface ChainLogger {
@@ -126,12 +141,6 @@ declare function next(options?: NextOptions): NextResult;
126
141
  */
127
142
  declare function isNextResult(value: unknown): value is NextResult;
128
143
 
129
- /**
130
- * Creates an isolated per-request context instance.
131
- * Backed by Map to eliminate prototype pollution risks.
132
- */
133
- declare function createProxyContext(): ProxyContext;
134
-
135
144
  /**
136
145
  * Creates a reusable, scope-aware proxy rule function.
137
146
  *
@@ -154,12 +163,38 @@ type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<NextRes
154
163
  * i18nRule,
155
164
  * ])
156
165
  */
166
+ /** @deprecated Use chain(). Plain functions here receive (request, context, event). */
157
167
  declare function proxyChain(entries: Entry<ProxyContext>[]): ProxyHandler;
158
168
  declare function proxyChain(options: ProxyChainOptions<ProxyContext>, entries: Entry<ProxyContext>[]): ProxyHandler;
159
169
  declare function proxyChain<TContext>(options: ProxyChainOptions<TContext> & {
160
170
  createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
161
171
  }, entries: Entry<TContext>[]): ProxyHandler;
162
172
 
173
+ /** Scope for a tuple entry: `[handler, scope]`. A string, RegExp, or array is shorthand for `include`. */
174
+ type ChainScope = Omit<ProxyPathFilter, 'name'> | PathMatcher | readonly PathMatcher[];
175
+ /** One entry of chain(): a native handler, a defineProxy() rule, a rule object, or a scoped tuple. */
176
+ type ChainEntry<TContext = ProxyContext> = NativeProxy<TContext> | ContextRuleEntry<TContext> | ProxyRule<TContext> | readonly [NativeProxy<TContext> | ContextRuleEntry<TContext>, ChainScope];
177
+ /**
178
+ * Composes native Next.js proxy handlers and optional rules into one proxy.
179
+ *
180
+ * - A plain function receives `(request, event)`, exactly like a native `proxy.ts` export.
181
+ * - A `defineProxy()` rule receives `(request, context, event)`.
182
+ * - `[handler, scope]` runs the handler only for matching paths or hosts.
183
+ *
184
+ * @example
185
+ * export default chain([intlProxy, [authProxy, { include: '/dashboard/**' }]])
186
+ */
187
+ declare function chain(entries: readonly ChainEntry<ProxyContext>[], options?: ProxyChainOptions<ProxyContext>): ReturnType<typeof proxyChain>;
188
+ declare function chain<TContext>(entries: readonly ChainEntry<TContext>[], options: ProxyChainOptions<TContext> & {
189
+ createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
190
+ }): ReturnType<typeof proxyChain>;
191
+
192
+ /**
193
+ * Creates an isolated per-request context instance.
194
+ * Backed by Map to eliminate prototype pollution risks.
195
+ */
196
+ declare function createProxyContext(): ProxyContext;
197
+
163
198
  /**
164
199
  * Builds a compiled Host matcher RegExp from domain names, `*.example.com` wildcards, or regex patterns.
165
200
  */
@@ -178,4 +213,4 @@ declare class RuleTimeoutError extends Error {
178
213
  constructor(ruleName: string, timeoutMs: number);
179
214
  }
180
215
 
181
- export { type ChainLogger, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
216
+ export { type ChainEntry, type ChainLogger, type ChainScope, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NativeProxy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, chain, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
package/dist/index.js CHANGED
@@ -20,6 +20,7 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
20
20
  "x-middleware-next",
21
21
  "x-middleware-override-headers"
22
22
  ]);
23
+ var CONTEXT_RULE = /* @__PURE__ */ Symbol.for("proxy-chain.context-rule");
23
24
 
24
25
  // src/core/actions.ts
25
26
  function next(options = {}) {
@@ -29,14 +30,14 @@ function isNextResult(value) {
29
30
  return typeof value === "object" && value !== null && NEXT in value;
30
31
  }
31
32
 
33
+ // src/core/engine.ts
34
+ import { NextRequest, NextResponse as NextResponse2 } from "next/server";
35
+
32
36
  // src/core/context.ts
33
37
  function createProxyContext() {
34
38
  return /* @__PURE__ */ new Map();
35
39
  }
36
40
 
37
- // src/core/engine.ts
38
- import { NextRequest, NextResponse as NextResponse2 } from "next/server";
39
-
40
41
  // src/core/headers.ts
41
42
  function normalizeHeaderName(name) {
42
43
  return name.toLowerCase();
@@ -183,16 +184,20 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
183
184
  function physicalFolderPrefix(raw) {
184
185
  return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
185
186
  }
187
+ function isInsideFolder(pathname, folder) {
188
+ if (folder === "/") return true;
189
+ return pathname === folder || pathname.startsWith(`${folder}/`);
190
+ }
186
191
  function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
187
192
  try {
188
193
  const parsed = new URL(rewriteUrl, baseUrl);
189
- if (!parsed.pathname.startsWith(folder)) {
194
+ if (!isInsideFolder(parsed.pathname, folder)) {
190
195
  parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
191
196
  return parsed.toString();
192
197
  }
193
198
  return rewriteUrl;
194
199
  } catch {
195
- if (!rewriteUrl.startsWith(folder)) {
200
+ if (!isInsideFolder(rewriteUrl, folder)) {
196
201
  return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
197
202
  }
198
203
  return rewriteUrl;
@@ -457,7 +462,8 @@ function runOverrideProbe() {
457
462
  const testRes = NextResponse.next({
458
463
  request: { headers: new Headers({ "x-proxy-chain-probe": "1" }) }
459
464
  });
460
- return testRes.headers.get("x-middleware-next") === "1";
465
+ const overridden = (testRes.headers.get("x-middleware-override-headers") ?? "").split(",").map((name) => name.trim());
466
+ return testRes.headers.get("x-middleware-next") === "1" && overridden.includes("x-proxy-chain-probe") && testRes.headers.get("x-middleware-request-x-proxy-chain-probe") === "1";
461
467
  }
462
468
  function throwForCachedProbe(probe) {
463
469
  if (probe.kind === "unsupported") throw new Error(UNSUPPORTED_OVERRIDE_MSG);
@@ -567,8 +573,19 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
567
573
  for (const key of seenHeaders) {
568
574
  if (!headers.has(key)) dropHeaders.push(key);
569
575
  }
570
- applyMergedToResponse(res, headers, cookies, dropHeaders);
571
- return res;
576
+ try {
577
+ applyMergedToResponse(res, headers, cookies, dropHeaders);
578
+ return res;
579
+ } catch (err) {
580
+ if (!(err instanceof TypeError)) throw err;
581
+ const copy = new Response(res.body, {
582
+ status: res.status,
583
+ statusText: res.statusText,
584
+ headers: new Headers(res.headers)
585
+ });
586
+ applyMergedToResponse(copy, headers, cookies, dropHeaders);
587
+ return copy;
588
+ }
572
589
  }
573
590
 
574
591
  // src/core/timeout.ts
@@ -639,6 +656,7 @@ function defineProxy(nameOrRun, maybeRun) {
639
656
  value: defaultName ?? "",
640
657
  configurable: true
641
658
  });
659
+ Object.defineProperty(proxy, CONTEXT_RULE, { value: true });
642
660
  return proxy;
643
661
  }
644
662
  function resolveConfig(overrides, fallbackCreateContext) {
@@ -695,6 +713,15 @@ function proxyChain(optionsOrEntries, maybeEntries) {
695
713
  let pendingRewriteUrl = null;
696
714
  const headerWrites = [];
697
715
  const cookieWrites = [];
716
+ const failClosed = () => finalizeResponse(
717
+ safeInternalError(),
718
+ headerWrites,
719
+ cookieWrites,
720
+ headerMergeStrategy,
721
+ cookieMergeStrategy,
722
+ logger,
723
+ debug
724
+ );
698
725
  const materializeRequest = () => {
699
726
  if (!pendingRequestOverrides) return currentReq;
700
727
  if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
@@ -721,13 +748,13 @@ function proxyChain(optionsOrEntries, maybeEntries) {
721
748
  const recoverRuleError = async (err, i, label, req2, startedAt) => {
722
749
  if (!config.onError) {
723
750
  logger.error({ rule: label, err }, "rule threw");
724
- return { response: safeInternalError() };
751
+ return { response: failClosed() };
725
752
  }
726
753
  try {
727
754
  const recovered = await config.onError(err, i, req2, ctx);
728
- if (recovered == null) return { response: safeInternalError() };
755
+ if (recovered == null) return { response: failClosed() };
729
756
  if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
730
- if (!(recovered instanceof Response)) return { response: safeInternalError() };
757
+ if (!(recovered instanceof Response)) return { response: failClosed() };
731
758
  stripRoutingOverrides(recovered);
732
759
  headerWrites.push({
733
760
  ruleIndex: i,
@@ -767,7 +794,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
767
794
  };
768
795
  } catch (onErrorErr) {
769
796
  logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
770
- return { response: safeInternalError() };
797
+ return { response: failClosed() };
771
798
  }
772
799
  };
773
800
  try {
@@ -895,19 +922,20 @@ function proxyChain(optionsOrEntries, maybeEntries) {
895
922
  finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
896
923
  } else {
897
924
  const currentPath = finalReq.nextUrl.pathname;
898
- if (!currentPath.startsWith(cleanFolder)) {
925
+ if (!isInsideFolder(currentPath, cleanFolder)) {
899
926
  const targetUrl = finalReq.nextUrl.clone();
900
927
  targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
901
928
  finalRewriteUrl = targetUrl.toString();
902
929
  }
903
930
  }
904
931
  }
932
+ const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
905
933
  let final;
906
934
  if (finalRewriteUrl) {
907
935
  const rewriteTarget = new URL(finalRewriteUrl, finalReq.url);
908
- final = NextResponse2.rewrite(rewriteTarget, { request: { headers: finalReq.headers } });
936
+ final = NextResponse2.rewrite(rewriteTarget, requestInit);
909
937
  } else {
910
- final = NextResponse2.next({ request: { headers: finalReq.headers } });
938
+ final = NextResponse2.next(requestInit);
911
939
  }
912
940
  return finalizeResponse(
913
941
  final,
@@ -938,12 +966,45 @@ function proxyChain(optionsOrEntries, maybeEntries) {
938
966
  } catch {
939
967
  }
940
968
  }
941
- return safeInternalError();
969
+ return failClosed();
942
970
  }
943
971
  };
944
972
  }
973
+
974
+ // src/core/chain.ts
975
+ function isContextRule(value) {
976
+ return typeof value === "function" && value[CONTEXT_RULE] === true;
977
+ }
978
+ function isScopeObject2(value) {
979
+ return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
980
+ }
981
+ function toFilter(scope) {
982
+ if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
983
+ return { include: scope };
984
+ }
985
+ function fromNative(handler) {
986
+ const run = (req, ctx, event) => handler(req, event, ctx);
987
+ const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
988
+ return { run, name };
989
+ }
990
+ function toEntry(entry) {
991
+ if (Array.isArray(entry)) {
992
+ const [target, scope] = entry;
993
+ const filter = toFilter(scope);
994
+ if (isContextRule(target)) return target(filter);
995
+ return withPaths(fromNative(target), filter);
996
+ }
997
+ if (isContextRule(entry)) return entry;
998
+ if (typeof entry === "function") return fromNative(entry);
999
+ return entry;
1000
+ }
1001
+ function chain(entries, options) {
1002
+ const normalized = entries.map((entry) => toEntry(entry));
1003
+ return proxyChain(options ?? {}, normalized);
1004
+ }
945
1005
  export {
946
1006
  RuleTimeoutError,
1007
+ chain,
947
1008
  createProxyContext,
948
1009
  defineProxy,
949
1010
  host,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klnap/next-proxy-chain",
3
- "version": "1.0.6",
3
+ "version": "1.1.0",
4
4
  "description": "Compose independent request rules for Next.js proxy.ts and middleware.ts.",
5
5
  "repository": {
6
6
  "type": "git",