@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/dist/index.js CHANGED
@@ -1,35 +1,3 @@
1
- // src/core/constants.ts
2
- var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
3
- var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
4
- "host",
5
- "connection",
6
- "keep-alive",
7
- "proxy-authenticate",
8
- "proxy-authorization",
9
- "te",
10
- "trailer",
11
- "transfer-encoding",
12
- "upgrade",
13
- "content-length",
14
- "cookie",
15
- "authorization",
16
- "x-forwarded-host",
17
- "x-forwarded-for",
18
- "x-forwarded-proto",
19
- "x-real-ip",
20
- "x-middleware-next",
21
- "x-middleware-override-headers"
22
- ]);
23
- var DEFINED_HANDLER = /* @__PURE__ */ Symbol.for("proxy-chain.defined-handler");
24
-
25
- // src/core/actions.ts
26
- function next(options = {}) {
27
- return { [NEXT]: true, ...options };
28
- }
29
- function isNextResult(value) {
30
- return typeof value === "object" && value !== null && NEXT in value;
31
- }
32
-
33
1
  // src/core/engine.ts
34
2
  import { NextRequest, NextResponse as NextResponse2 } from "next/server.js";
35
3
 
@@ -116,42 +84,12 @@ function createHandlerContext(metadata, applicationState, signal) {
116
84
  }
117
85
 
118
86
  // src/core/headers.ts
119
- function normalizeHeaderName(name) {
120
- return name.toLowerCase();
121
- }
122
- function headersInitToHeaders(init) {
123
- return new Headers(init);
124
- }
125
87
  function headersDiffer(base, overrides) {
126
88
  for (const [key, value] of overrides.entries()) {
127
89
  if (base.get(key) !== value) return true;
128
90
  }
129
91
  return false;
130
92
  }
131
- function isRequestHeaderAllowed(name, policy = {}) {
132
- const key = normalizeHeaderName(name);
133
- const allowed = new Set((policy.allowed ?? []).map(normalizeHeaderName));
134
- if (allowed.has(key)) return true;
135
- if (key.startsWith("x-middleware-")) return false;
136
- const blocked = /* @__PURE__ */ new Set([
137
- ...DEFAULT_BLOCKED_REQUEST_HEADERS.map(normalizeHeaderName),
138
- ...(policy.blocked ?? []).map(normalizeHeaderName)
139
- ]);
140
- return !blocked.has(key);
141
- }
142
- function mergeRequestHeaderOverrides(target, overrides, policy = {}) {
143
- const dropped = [];
144
- let applied = 0;
145
- overrides.forEach((value, key) => {
146
- if (!isRequestHeaderAllowed(key, policy)) {
147
- dropped.push(key);
148
- return;
149
- }
150
- target.set(key, value);
151
- applied++;
152
- });
153
- return { applied, dropped };
154
- }
155
93
  function parseCookieName(setCookie) {
156
94
  const eq = setCookie.indexOf("=");
157
95
  return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
@@ -572,16 +510,14 @@ function path(pattern) {
572
510
  if (pattern instanceof RegExp) return compileRegexPath(pattern);
573
511
  return compileStringPath(pattern);
574
512
  }
575
- function toPathRegex(matcher) {
513
+ function toPathRegexes(matcher) {
576
514
  const list = Array.isArray(matcher) ? matcher : [matcher];
577
- const regexes = list.map((m) => path(m));
578
- if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
579
- return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
515
+ return list.map((m) => toStatelessRegExp(path(m)));
580
516
  }
581
517
  function compileScopes(input) {
582
518
  if (input == null) return void 0;
583
519
  const list = Array.isArray(input) ? input : [input];
584
- const compilePath = (matcher) => toPathRegex(matcher);
520
+ const compilePath = (matcher) => toPathRegexes(matcher);
585
521
  const compiled = [];
586
522
  for (const item of list) {
587
523
  if (typeof item === "string" || item instanceof RegExp) {
@@ -607,7 +543,7 @@ function scopeMatches(pathname, hostname, scope) {
607
543
  if (!hostname || !scope.host.test(hostname)) return false;
608
544
  }
609
545
  if (scope.path) {
610
- if (!scope.path.test(pathname)) return false;
546
+ if (!scope.path.some((alternative) => alternative.test(pathname))) return false;
611
547
  }
612
548
  return true;
613
549
  }
@@ -622,12 +558,12 @@ function toRule(entry) {
622
558
  const harden = (scopes) => scopes?.map((s) => {
623
559
  if (!s.host && !s.path) {
624
560
  throw new Error(
625
- "[proxy-chain] include/exclude scope needs `host` or `path`. Build scopes with path() or host()."
561
+ "[proxy-chain] include/exclude scope needs a path, host, or host/path object."
626
562
  );
627
563
  }
628
564
  return {
629
565
  host: s.host ? toStatelessRegExp(s.host) : void 0,
630
- path: s.path ? toStatelessRegExp(s.path) : void 0
566
+ path: s.path?.map(toStatelessRegExp)
631
567
  };
632
568
  });
633
569
  return {
@@ -641,23 +577,6 @@ function ruleLabel(rule, index) {
641
577
  const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
642
578
  return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
643
579
  }
644
- function withPaths(entry, filter) {
645
- const base = toRule(entry);
646
- const include = compileScopes(filter.include);
647
- const exclude = compileScopes(filter.exclude);
648
- const name = filter.name ?? base.name;
649
- assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
650
- return {
651
- run: base.run,
652
- include,
653
- exclude,
654
- name,
655
- debug: base.debug,
656
- timeout: base.timeout,
657
- when: base.when,
658
- diagnosticRules: { include: filter.include, exclude: filter.exclude }
659
- };
660
- }
661
580
  function ruleMatchReason(pathname, hostname, rule) {
662
581
  if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
663
582
  return "exclude-match";
@@ -688,7 +607,8 @@ function canonicalPathname(pathname) {
688
607
  return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
689
608
  }
690
609
  function scopeKey(scope) {
691
- return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
610
+ const path2 = scope.path?.map((alternative) => `${alternative.source}::${alternative.flags}`).join("&");
611
+ return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${path2 ?? "*"}`;
692
612
  }
693
613
  function assertIncludeExcludeNoOverlap(include, exclude, label) {
694
614
  if (!include?.length || !exclude?.length) return;
@@ -750,45 +670,21 @@ function assertOverrideMechanismSupported(strict = false) {
750
670
  return false;
751
671
  }
752
672
  }
753
- function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
754
- if (res == null) {
673
+ function resolveRuleResult(res) {
674
+ if (res === void 0) {
755
675
  return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
756
676
  }
757
- if (!isNextResult(res) && !(res instanceof Response)) {
677
+ if (!(res instanceof Response)) {
758
678
  throw new TypeError(
759
- `[proxy-chain] rule must return next(), a Response, or undefined. Got ${typeof res}.`
679
+ `[proxy-chain] rule must return a Response or undefined. Got ${typeof res}.`
760
680
  );
761
681
  }
762
- if (isNextResult(res)) {
763
- let request;
764
- if (res.request) {
765
- const filtered = new Headers();
766
- const { dropped } = mergeRequestHeaderOverrides(
767
- filtered,
768
- headersInitToHeaders(res.request),
769
- requestHeaderPolicy
770
- );
771
- if (debug && dropped.length) {
772
- logger.warn({ dropped }, "blocked request header mutation");
773
- }
774
- if ([...filtered.keys()].length) request = filtered;
775
- }
776
- const headerInit = res.headers ? headersInitToHeaders(res.headers) : void 0;
777
- return {
778
- kind: "continue",
779
- request,
780
- responseHeaders: headerInit ? responseHeaderItems(headerInit) : /* @__PURE__ */ new Map(),
781
- cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
782
- };
783
- }
784
682
  if (res instanceof NextResponse && res.headers.get("x-middleware-next") === "1") {
785
683
  let request;
786
684
  const decoded = decodeOverriddenRequestHeaders(res.headers);
787
685
  const hasRequestOverride = res.headers.has("x-middleware-override-headers");
788
686
  if (hasRequestOverride) {
789
- const target = new Headers();
790
- mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
791
- request = target;
687
+ request = decoded;
792
688
  }
793
689
  return {
794
690
  kind: "continue",
@@ -804,9 +700,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
804
700
  const decoded = decodeOverriddenRequestHeaders(res.headers);
805
701
  const hasRequestOverride = res.headers.has("x-middleware-override-headers");
806
702
  if (hasRequestOverride) {
807
- const target = new Headers();
808
- mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
809
- request = target;
703
+ request = decoded;
810
704
  }
811
705
  return {
812
706
  kind: "continue",
@@ -1015,8 +909,11 @@ function safeLogger(logger) {
1015
909
  error: wrap("error")
1016
910
  };
1017
911
  }
1018
- function isNextResponse(value) {
1019
- return value instanceof NextResponse2 && value.headers.get("x-middleware-next") === "1";
912
+ function isTerminalRecovery(value) {
913
+ return value instanceof Response && resolveRuleResult(value).kind === "stop";
914
+ }
915
+ function isContinuingRecovery(value) {
916
+ return value instanceof Response && resolveRuleResult(value).kind === "continue";
1020
917
  }
1021
918
  function stripRoutingOverrides(res) {
1022
919
  const plain = !(res instanceof NextResponse2);
@@ -1043,7 +940,6 @@ function resolveConfig(overrides) {
1043
940
  headerMergeStrategy: "last-write-wins",
1044
941
  debug: false,
1045
942
  timeout: 0,
1046
- requestHeaderPolicy: {},
1047
943
  strictOverrideCheck: false,
1048
944
  tracePath: true,
1049
945
  ...rest,
@@ -1062,7 +958,6 @@ function executeChain(options, entries) {
1062
958
  cookieMergeStrategy,
1063
959
  headerMergeStrategy,
1064
960
  timeout,
1065
- requestHeaderPolicy,
1066
961
  strictOverrideCheck
1067
962
  } = config;
1068
963
  const debug = debugLevel !== false;
@@ -1167,16 +1062,7 @@ function executeChain(options, entries) {
1167
1062
  return currentReq;
1168
1063
  }
1169
1064
  const nextUrl = currentReq.nextUrl.clone();
1170
- const merged = new Headers();
1171
- if (replaceRequestHeaders) {
1172
- currentReq.headers.forEach((value, key) => {
1173
- if (!isRequestHeaderAllowed(key, requestHeaderPolicy)) merged.set(key, value);
1174
- });
1175
- } else {
1176
- currentReq.headers.forEach((value, key) => {
1177
- merged.set(key, value);
1178
- });
1179
- }
1065
+ const merged = replaceRequestHeaders ? new Headers() : new Headers(currentReq.headers);
1180
1066
  pendingRequestOverrides.forEach((v, k) => {
1181
1067
  merged.set(k, v);
1182
1068
  });
@@ -1267,7 +1153,7 @@ function executeChain(options, entries) {
1267
1153
  (signal) => errorHandler(err, i, req2, contextFor(signal))
1268
1154
  );
1269
1155
  if (timeoutError || requestCancelled) {
1270
- if (recovered instanceof Response && !isNextResponse(recovered)) {
1156
+ if (isTerminalRecovery(recovered)) {
1271
1157
  const response2 = stripRoutingOverrides(recovered);
1272
1158
  headerWrites.push({
1273
1159
  ruleIndex: i,
@@ -1322,17 +1208,8 @@ function executeChain(options, entries) {
1322
1208
  if (recovered == null) {
1323
1209
  return stopFailure(errorPolicy);
1324
1210
  }
1325
- if (isNextResult(recovered) || isNextResponse(recovered)) {
1326
- diagnostics?.push({
1327
- name: safeDiagnosticText(label, 64),
1328
- outcome: "recovered",
1329
- durationMs,
1330
- recovery: "continue",
1331
- policy: errorPolicy,
1332
- details
1333
- });
1334
- nextHandlerIndex = i + 1;
1335
- return { raw: recovered };
1211
+ if (isContinuingRecovery(recovered)) {
1212
+ return { raw: recovered, recovered: { durationMs, policy: errorPolicy, details } };
1336
1213
  }
1337
1214
  if (!(recovered instanceof Response)) {
1338
1215
  diagnostics?.push({
@@ -1441,6 +1318,7 @@ function executeChain(options, entries) {
1441
1318
  const effectiveTimeout = rule.timeout ?? timeout;
1442
1319
  let phase = rule.when ? "when" : "handler";
1443
1320
  let result;
1321
+ let recoveredRule;
1444
1322
  try {
1445
1323
  result = await runInExecutionScope(
1446
1324
  req.signal,
@@ -1482,17 +1360,19 @@ function executeChain(options, entries) {
1482
1360
  );
1483
1361
  if ("response" in recovered) return recovered.response;
1484
1362
  result = { kind: "result", raw: recovered.raw };
1363
+ recoveredRule = recovered.recovered;
1485
1364
  }
1486
1365
  let raw = result.raw;
1487
1366
  let duration2 = monotonicNow() - executionStartedAt;
1488
1367
  let outcome;
1489
1368
  try {
1490
- outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
1369
+ outcome = resolveRuleResult(raw);
1491
1370
  } catch (err) {
1492
1371
  const recovered = await recoverRuleError(err, i, label, activeReq, duration2, "result");
1493
1372
  if ("response" in recovered) return recovered.response;
1494
1373
  raw = recovered.raw;
1495
- outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
1374
+ recoveredRule = recovered.recovered;
1375
+ outcome = resolveRuleResult(raw);
1496
1376
  }
1497
1377
  if (outcome.kind === "continue") {
1498
1378
  if (outcome.rewriteUrl) {
@@ -1513,7 +1393,16 @@ function executeChain(options, entries) {
1513
1393
  headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
1514
1394
  cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
1515
1395
  }
1516
- if (diagnostics?.at(-1)?.outcome !== "recovered") {
1396
+ if (recoveredRule) {
1397
+ diagnostics?.push({
1398
+ name: safeDiagnosticText(label, 64),
1399
+ outcome: "recovered",
1400
+ durationMs: recoveredRule.durationMs,
1401
+ recovery: outcome.rewriteUrl ? "rewrite" : "continue",
1402
+ policy: recoveredRule.policy,
1403
+ details: recoveredRule.details
1404
+ });
1405
+ } else {
1517
1406
  diagnostics?.push(
1518
1407
  outcome.rewriteUrl ? {
1519
1408
  name: safeDiagnosticText(label, 64),
@@ -1525,7 +1414,7 @@ function executeChain(options, entries) {
1525
1414
  } : {
1526
1415
  name: safeDiagnosticText(label, 64),
1527
1416
  outcome: "continue",
1528
- source: isNextResult(raw) ? "next()" : raw instanceof NextResponse2 && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1417
+ source: raw instanceof NextResponse2 && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1529
1418
  durationMs: duration2,
1530
1419
  details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
1531
1420
  }
@@ -1624,7 +1513,7 @@ function executeChain(options, entries) {
1624
1513
  req.signal,
1625
1514
  (signal) => config.onError(err, -1, materializeRequest(), contextFor(signal))
1626
1515
  );
1627
- if (recovered instanceof Response && !isNextResponse(recovered)) {
1516
+ if (isTerminalRecovery(recovered)) {
1628
1517
  const response = stripRoutingOverrides(recovered);
1629
1518
  return finish(
1630
1519
  finalizeResponse(
@@ -1649,47 +1538,28 @@ function executeChain(options, entries) {
1649
1538
  };
1650
1539
  }
1651
1540
 
1652
- // src/core/chain.ts
1653
- function isDefinedHandler(value) {
1654
- return typeof value === "object" && value !== null && value[DEFINED_HANDLER] === true;
1655
- }
1656
- function isScopeObject2(value) {
1657
- return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
1658
- }
1659
- function toFilter(scope) {
1660
- if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
1661
- return { include: scope };
1662
- }
1663
- function fromNative(handler) {
1664
- const run = (req, ctx, event) => handler(req, event, ctx);
1665
- const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
1666
- return { run, name };
1667
- }
1668
- function toEntry(entry) {
1669
- if (Array.isArray(entry)) {
1670
- const [target, scope] = entry;
1671
- const filter = toFilter(scope);
1672
- if (isDefinedHandler(target)) return withPaths(target, filter);
1673
- return withPaths(fromNative(target), filter);
1674
- }
1675
- if (isDefinedHandler(entry)) return entry;
1676
- if (typeof entry === "function") return fromNative(entry);
1677
- throw new TypeError(
1678
- "[proxy-chain] chain entries must be native handlers or defineHandler() results"
1679
- );
1680
- }
1681
- function chain(entries, options) {
1682
- const normalized = entries.map((entry) => toEntry(entry));
1683
- return executeChain(options ?? {}, normalized);
1684
- }
1685
-
1686
1541
  // src/core/handler.ts
1687
- function defineHandler(options) {
1542
+ function assertHandlerConfig(options) {
1543
+ if (!options || typeof options !== "object" || typeof options.name !== "string" || options.name.trim() === "" || typeof options.handle !== "function") {
1544
+ throw new TypeError("[proxy-chain] configured handlers require a non-empty name and handle");
1545
+ }
1546
+ if ("handler" in options) {
1547
+ throw new TypeError(
1548
+ "[proxy-chain] configured handler property 'handler' is unsupported; use 'handle'"
1549
+ );
1550
+ }
1551
+ if ("config" in options || "options" in options) {
1552
+ throw new TypeError("[proxy-chain] handler configuration must use top-level options");
1553
+ }
1688
1554
  assertValidTimeout(options.timeout);
1555
+ }
1556
+ function toHandlerRule(options) {
1557
+ assertHandlerConfig(options);
1558
+ const { handle } = options;
1689
1559
  const include = compileScopes(options.rules?.include);
1690
1560
  const exclude = compileScopes(options.rules?.exclude);
1691
- const rule = {
1692
- run: (request, context, event) => options.handler(request, event, context),
1561
+ return {
1562
+ run: (request, context, event) => handle(request, event, context),
1693
1563
  name: options.name,
1694
1564
  include,
1695
1565
  exclude,
@@ -1702,14 +1572,31 @@ function defineHandler(options) {
1702
1572
  exclude: options.rules?.exclude
1703
1573
  }
1704
1574
  };
1705
- return { ...rule, [DEFINED_HANDLER]: true };
1575
+ }
1576
+ function defineHandler(options) {
1577
+ assertHandlerConfig(options);
1578
+ return options;
1579
+ }
1580
+
1581
+ // src/core/chain.ts
1582
+ function fromNative(handle) {
1583
+ const run = (req, ctx, event) => handle(req, event, ctx);
1584
+ const name = handle.name && handle.name !== "proxy" ? handle.name : void 0;
1585
+ return { run, name };
1586
+ }
1587
+ function toEntry(entry) {
1588
+ if (typeof entry === "function") return fromNative(entry);
1589
+ if (Array.isArray(entry)) {
1590
+ throw new TypeError("[proxy-chain] tuple entries are not supported; use a configured handler");
1591
+ }
1592
+ if (entry && typeof entry === "object") return toHandlerRule(entry);
1593
+ throw new TypeError("[proxy-chain] chain entries must be native handlers or configured handlers");
1594
+ }
1595
+ function chain(entries, options) {
1596
+ const normalized = entries.map((entry) => toEntry(entry));
1597
+ return executeChain(options ?? {}, normalized);
1706
1598
  }
1707
1599
  export {
1708
- RuleTimeoutError,
1709
1600
  chain,
1710
- defineHandler,
1711
- host,
1712
- isNextResult,
1713
- next,
1714
- path
1601
+ defineHandler
1715
1602
  };
package/docs/api.md ADDED
@@ -0,0 +1,190 @@
1
+ # API reference
2
+
3
+ The runtime entry exports two functions:
4
+
5
+ ```ts
6
+ import { chain, defineHandler } from "@klnap/next-proxy-chain";
7
+ ```
8
+
9
+ Next.js owns HTTP responses. Use `NextResponse` from `next/server` and standard Web `Response`, `Headers`, and `AbortSignal`.
10
+
11
+ ## `chain()`
12
+
13
+ ```ts
14
+ chain<TContext extends object = object>(
15
+ entries: readonly ChainEntry<TContext>[],
16
+ options?: ChainOptions<TContext>,
17
+ ): (request: NextRequest, event: NextFetchEvent) => Promise<NextResponse | Response>
18
+ ```
19
+
20
+ `chain()` accepts native handler functions and configured handler objects. Entries run sequentially. A `NextResponse.next()` or `undefined` continues; redirects and terminal responses stop.
21
+
22
+ ## `defineHandler()`
23
+
24
+ ```ts
25
+ defineHandler<TContext extends object = object>(
26
+ options: HandlerConfig<TContext>,
27
+ ): HandlerConfig<TContext>
28
+ ```
29
+
30
+ It validates and returns the same configuration object. Inline and reusable configurations have the same type and normalization behavior.
31
+
32
+ ## Configured handler
33
+
34
+ ```ts
35
+ type HandlerConfig<TContext extends object = object> = {
36
+ name: string;
37
+ rules?: {
38
+ include?: RouteScopeList;
39
+ exclude?: RouteScopeList;
40
+ when?: HandlerWhen<TContext>;
41
+ };
42
+ timeout?: number;
43
+ debug?: DebugLevel;
44
+ onError?: OnErrorHandler<TContext>;
45
+ handle: NativeProxy<TContext>;
46
+ };
47
+ ```
48
+
49
+ `name` must be a non-empty string. `handle` must be a function. `rules`, `timeout`, `debug`, and `onError` are optional. `handle` appears last in examples by convention, not requirement.
50
+
51
+ ```ts
52
+ defineHandler({
53
+ name: "authentication",
54
+ rules: { include: "/dashboard/**" },
55
+ timeout: 500,
56
+ debug: true,
57
+ onError: handleError,
58
+ handle: async (request, event, context) => {
59
+ return authenticate(request, event, context.signal);
60
+ },
61
+ });
62
+ ```
63
+
64
+ Arrow functions are the primary convention for `handle`, `when`, and `onError`. Async functions, function references, and object method syntax also satisfy the contract.
65
+
66
+ ## Native handler
67
+
68
+ ```ts
69
+ type NativeProxy<TContext extends object = object> = (
70
+ request: NextRequest,
71
+ event: NextFetchEvent,
72
+ context: HandlerContext<TContext>,
73
+ ) =>
74
+ | NextResponse
75
+ | Response
76
+ | undefined
77
+ | void
78
+ | Promise<NextResponse | Response | undefined | void>;
79
+ ```
80
+
81
+ Two-argument Next.js handlers remain composable. The chain adds context as the optional third callback argument and passes through the original `event`.
82
+
83
+ ## Matching
84
+
85
+ `Next.js config.matcher` filters whether the entrypoint runs. Handler `rules` filter configured handlers after entrypoint invocation.
86
+
87
+ - `include` and `exclude` accept a path string, `RegExp`, or objects with `path` and/or `host`.
88
+ - `*` matches one path segment. `**` matches zero or more segments.
89
+ - `exclude` takes precedence over `include`.
90
+ - `when(request, event, context)` may return a boolean or `Promise<boolean>`.
91
+ - Matching uses the effective request at each handler's turn. A continued rewrite changes later path matching and the query visible to predicates; original context metadata remains unchanged.
92
+ - Rewrites do not change the host used for matching. Host scopes read the effective `host` header, falling back to `x-forwarded-host`; a prior native request-header replacement of either header changes later host matching.
93
+
94
+ Host matcher strings compare case-insensitively and ignore ports. Host wildcards match one DNS label. See [Concepts](concepts.md#matching) for examples.
95
+
96
+ ## Return values
97
+
98
+ | Handler returns | Chain behavior |
99
+ | ---------------------------- | ------------------------------------------------- |
100
+ | `undefined` | Continue to the next handler. |
101
+ | `NextResponse.next()` | Compose HTTP effects and continue. |
102
+ | `NextResponse.rewrite(url)` | Stage the rewrite and continue to later handlers. |
103
+ | `NextResponse.redirect(url)` | Stop and redirect. |
104
+ | Terminal `Response` | Stop and return the response. |
105
+
106
+ Only `NextResponse` routing responses are interpreted as continuation or rewrite instructions. A plain `Response` remains terminal, even if it contains Next.js routing headers.
107
+
108
+ `NextResponse.rewrite()` continues only for a successful rewrite response. Non-success responses are terminal. Redirects are terminal.
109
+
110
+ ## Request headers
111
+
112
+ Use native `NextResponse.next({ request: { headers } })`. Next.js treats `headers` as the replacement request-header set, not a partial merge. Clone the effective request headers to preserve them:
113
+
114
+ ```ts
115
+ const headers = new Headers(request.headers);
116
+ headers.set("x-request-id", context.requestId);
117
+ return NextResponse.next({ request: { headers } });
118
+ ```
119
+
120
+ Removing a header means deleting it from the `Headers` instance before returning it. A replacement that omits a prior request header deletes that header downstream.
121
+
122
+ Each continued native override becomes the effective request seen by later rules. The engine reconstructs `NextRequest` using Next.js's encoded override metadata, while retaining staged rewrite URL state, request signal, and original chain metadata. Request headers remain separate from client-facing response headers.
123
+
124
+ There is no package-level request-header allow/deny policy. Handler code explicitly chooses the forwarded header set. Validate untrusted values before adding or changing headers.
125
+
126
+ ## Response headers and cookies
127
+
128
+ Mutate the native response:
129
+
130
+ ```ts
131
+ const response = NextResponse.next();
132
+ response.headers.set("x-content-type-options", "nosniff");
133
+ response.cookies.set("locale", "en");
134
+ return response;
135
+ ```
136
+
137
+ Continued response headers and cookies compose onto the final response. The default merge strategy is last-write-wins. `headerMergeStrategy` and `cookieMergeStrategy` can select `"first-write-wins"` or a custom resolver; returning `null` from a resolver removes that header or cookie identity.
138
+
139
+ Cookie identity includes cookie name, domain, and path. Distinct paths remain distinct.
140
+
141
+ ## Context and cancellation
142
+
143
+ `HandlerContext<TContext>` contains:
144
+
145
+ - `requestId`: generated `req_` identifier.
146
+ - `startedAt`: request start time.
147
+ - `elapsedMs`: elapsed request duration.
148
+ - `originalUrl`, `originalPathname`, and `originalHostname`: original request metadata.
149
+ - `signal`: execution-scoped `AbortSignal`.
150
+ - Custom properties from `TContext`.
151
+
152
+ Custom state is shared between handlers for one request and isolated across requests. Properties may be `undefined` until initialized. Context and request IDs are not forwarded to route handlers automatically.
153
+
154
+ ## Errors and timeouts
155
+
156
+ `timeout` is a per-handler execution budget in milliseconds; `0` disables timeouts. A handler's timeout overrides the chain timeout. The handler's predicate shares its budget. Timeout aborts the execution signal and stops the chain.
157
+
158
+ Handler-level `onError` takes precedence over chain-level `onError`. For ordinary errors, returning `NextResponse.next()` or a successful `NextResponse.rewrite()` continues after the failed handler; a rewrite is staged like a normal rewrite. Returning any other `Response` terminates with that response. Returning `undefined`, `void`, or `null`, throwing, or returning an unsupported value fails closed.
159
+
160
+ For timeout, request cancellation, and engine-level failures, recovery accepts only a terminal Web `Response`, including a redirect. `NextResponse.next()` and successful `NextResponse.rewrite()` are rejected because they would resume routing. A rejected timeout or engine-level recovery returns `500`. Without recovery, timeout returns `500`. Cancellation stops the package chain and returns a native `NextResponse.next()` handoff; Next.js may continue downstream routing, so this is not a fail-closed response. Error diagnostics record the chosen recovery policy.
161
+
162
+ ## Chain options
163
+
164
+ | Option | Default | Meaning |
165
+ | --------------------- | ------------------- | --------------------------------------------------------------------------------------------------- |
166
+ | `timeout` | `0` | Per-handler deadline in milliseconds. |
167
+ | `debug` | `false` | Disable logs, or select `true`, `"compact"`, `"detailed"`, or `"verbose"`. |
168
+ | `logger` | Console logger | Logger with `debug`, `info`, `warn`, and `error` methods. |
169
+ | `onError` | None | Chain-level error recovery. Handler-level `onError` takes precedence. |
170
+ | `onTrace` | None | Receives structured request traces. |
171
+ | `tracePath` | `true` | Include the original request pathname in the top-level structured trace and formatted request line. |
172
+ | `headerMergeStrategy` | `"last-write-wins"` | Resolve response-header conflicts. |
173
+ | `cookieMergeStrategy` | `"last-write-wins"` | Resolve cookie conflicts. |
174
+ | `strictOverrideCheck` | `false` | Throw at chain creation if native Next.js request-header override metadata cannot be verified. |
175
+
176
+ Handler `timeout` and `debug` override their chain-level values. Chain-level `onError` is used only when a handler does not define its own.
177
+
178
+ `strictOverrideCheck` tests whether the active Next.js `NextResponse.next()` encodes a sentinel request-header override. The probe runs when the first chain is constructed and caches its result for that package module. A successful probe is silent and leaves normal native header replacement behavior unchanged.
179
+
180
+ If the probe reports unsupported behavior or throws, `strictOverrideCheck: true` throws during chain construction. With the default `false`, an uncached failed probe warns and chain construction continues; later chains reuse the result without probing again. The package does not emulate the override mechanism. Request-header replacements may then be missing from later handlers or downstream Next.js code. Use `true` to fail fast when the application depends on native request-header forwarding.
181
+
182
+ The probe checks Next.js's generated override metadata. It does not verify that the deployed runtime later applies that metadata.
183
+
184
+ `tracePath: false` removes only the original request pathname from `ChainTrace.pathname` and the formatted request line. It does not remove paths in matched scope details or rewrite and redirect destinations. Destination query values are replaced with `?[query]`.
185
+
186
+ ## Public types
187
+
188
+ The package exports `ChainEntry`, `ChainOptions`, `HandlerConfig`, `NativeProxy`, `OnErrorHandler`, `OnErrorResult`, `HandlerContext`, `RequestMetadata`, matcher types, and structured diagnostic types.
189
+
190
+ It exports no helper-specific continuation token, response wrapper, or request-header policy.