@klnap/next-proxy-chain 1.0.3 → 1.0.5
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 +62 -0
- package/LICENSE +1 -1
- package/README.md +72 -54
- package/dist/index.cjs +333 -316
- package/dist/index.d.cts +57 -161
- package/dist/index.d.ts +57 -161
- package/dist/index.js +332 -285
- package/package.json +16 -11
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@klnap/next-proxy-chain` will be documented in this file.
|
|
4
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
5
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [1.0.5] - 2026-10-29
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Host folder prefix rewrite logic lives in a dedicated module with unit coverage; runtime behavior is unchanged.
|
|
14
|
+
- README lists peer requirements and trims redundant install/badge copy.
|
|
15
|
+
|
|
16
|
+
## [1.0.4] - 2026-08-27
|
|
17
|
+
|
|
18
|
+
### Breaking
|
|
19
|
+
|
|
20
|
+
- `onError` returning `undefined` / `void` / `null` now **fails closed** with a 500. Continue only by returning `next()`.
|
|
21
|
+
- `x-internal-host-folder` is no longer a magic routing header. Enable it with `hostFolderHeader: "x-internal-host-folder"`.
|
|
22
|
+
- Public exports are limited to the documented API. Internals (`mergeWrites`, `compileScopes`, `withRuleTimeout`, `./core`, …) are no longer exported.
|
|
23
|
+
- Custom `TContext` requires `createContext`. `proxyChain<{ user: string }>(rules)` without a factory is a type error.
|
|
24
|
+
- Removed `PathOptions` and `pathOptions`; `path()` no longer accepts a `locales` option. Match locale-prefixed routes in the pattern string or RegExp.
|
|
25
|
+
- `ruleTimeoutMs`: passing `NaN`, `Infinity`, or `-Infinity` now throws a `RangeError` at proxy-chain configuration time instead of silently disabling the timeout. If you were relying on an unvalidated computed value (e.g. from `parseInt` without a fallback) resulting in a disabled timeout, this is a breaking change — validate your config value before passing it.
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- `path()` no longer drops `^` / `$` from user RegExp.
|
|
30
|
+
- Trailing `*` matches exactly one segment; `**` matches nested paths.
|
|
31
|
+
- `compileScopes()` runs RegExp matchers through `path()`.
|
|
32
|
+
- `next({ headers: { "set-cookie": … } })` reaches the final response.
|
|
33
|
+
- Cookies with the same name and different `Path` / `Domain` are not collapsed.
|
|
34
|
+
- Custom header merge returning `null` deletes the header from the terminal response.
|
|
35
|
+
- Rewrite continuation no longer mutates the incoming `NextRequest`.
|
|
36
|
+
- Timed-out rules no longer leave an unhandled rejection.
|
|
37
|
+
- `host("*.example.com")` matches one DNS label.
|
|
38
|
+
- `strictOverrideCheck` cache no longer pins the first call’s strictness for later calls.
|
|
39
|
+
|
|
40
|
+
### Changed
|
|
41
|
+
|
|
42
|
+
- `headerMergeStrategy` applies only to **response** headers. Request overrides stay last-write-wins.
|
|
43
|
+
- Package metadata: `repository`, `bugs`, `homepage`.
|
|
44
|
+
- Tests run on `bun:test`; removed Typedoc site from the package repo.
|
|
45
|
+
|
|
46
|
+
## [1.0.3] - 2026-08-26
|
|
47
|
+
|
|
48
|
+
npm patch. No detailed notes were kept for 1.0.1–1.0.3 at publish time.
|
|
49
|
+
|
|
50
|
+
## [1.0.0] - 2026-08-23
|
|
51
|
+
|
|
52
|
+
### Added
|
|
53
|
+
|
|
54
|
+
- Composable Edge-safe proxy pipeline via `proxyChain()`.
|
|
55
|
+
- Transparent Next.js pass-through detection on `x-middleware-next: 1` with request override extraction.
|
|
56
|
+
- Automatic filtering of internal `x-middleware-*` transport headers from client responses.
|
|
57
|
+
- Request header blocklist preventing rule injection of sensitive headers (`host`, `authorization`, `x-middleware-*`).
|
|
58
|
+
- Context threading via isolated per-request `Map` instances (`TContext`).
|
|
59
|
+
- Header and cookie accumulation with `last-write-wins`, `first-write-wins`, and custom merge strategies.
|
|
60
|
+
- Path and host scoping (`include`, `exclude`) with construction-time overlap validation.
|
|
61
|
+
- Cached startup self-test for `NextResponse.next()` request overrides.
|
|
62
|
+
- Error isolation with safe 500 fallback.
|
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
Composable request pipeline for Next.js middleware and proxy.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
`next` `>=15.0.0` (peer dependency).
|
|
8
10
|
|
|
9
11
|
---
|
|
10
12
|
|
|
@@ -16,27 +18,9 @@ Composable request pipeline for Next.js middleware and proxy.
|
|
|
16
18
|
- **Deterministic Header & Cookie Merging**: Propagate request header overrides downstream, deduplicate `Set-Cookie` headers, and merge response headers with configurable conflict strategies.
|
|
17
19
|
- **Route & Host Scoping**: Declarative path matching (globs, parameters, regex) and host filtering with `include` and `exclude` rules.
|
|
18
20
|
- **Safe Pattern Matching**: Normalizes stateful regular expressions to avoid `lastIndex`-related matching issues.
|
|
19
|
-
- **Explicit Flow Control**: Return `next({ request, headers })` to
|
|
20
|
-
- **Timeouts & Error Recovery**: Optional per-rule timeouts (`ruleTimeoutMs`)
|
|
21
|
-
- **Zero Runtime Dependencies**: Fully typed in TypeScript with no runtime dependencies.
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
## Installation
|
|
26
|
-
|
|
27
|
-
```bash
|
|
28
|
-
npm install @klnap/next-proxy-chain
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
Or with your preferred package manager:
|
|
32
|
-
|
|
33
|
-
```bash
|
|
34
|
-
pnpm add @klnap/next-proxy-chain
|
|
35
|
-
# or
|
|
36
|
-
bun add @klnap/next-proxy-chain
|
|
37
|
-
# or
|
|
38
|
-
yarn add @klnap/next-proxy-chain
|
|
39
|
-
```
|
|
21
|
+
- **Explicit Flow Control**: Return `next({ request, headers })` to continue, or a terminal `Response` / `NextResponse.redirect` / `NextResponse.json` to stop. `NextResponse.rewrite` **continues** the pipeline (rewrite is applied at the end unless a later rule stops).
|
|
22
|
+
- **Timeouts & Error Recovery**: Optional per-rule timeouts (`ruleTimeoutMs`). `onError` is fail-closed: returning nothing yields 500; return `next()` to continue; return a `Response` to stop.
|
|
23
|
+
- **Zero Runtime Dependencies**: Fully typed in TypeScript with no runtime dependencies (`next` is a peer).
|
|
40
24
|
|
|
41
25
|
---
|
|
42
26
|
|
|
@@ -103,10 +87,16 @@ const adminRule = apiAuth({
|
|
|
103
87
|
|
|
104
88
|
### Path Patterns
|
|
105
89
|
|
|
106
|
-
-
|
|
107
|
-
-
|
|
108
|
-
-
|
|
109
|
-
-
|
|
90
|
+
- `path("/api/*")` — exactly one segment (`/api/users` yes, `/api/users/123` no)
|
|
91
|
+
- `path("/docs/**")` — the prefix plus zero or more extra segments (`/docs`, `/docs/a/b`)
|
|
92
|
+
- `path("/users/:id")` — one segment (no capture groups; matching only)
|
|
93
|
+
- `path(/^\/foo$/)` — user anchors are kept (`/foo` yes, `/x/foo` no)
|
|
94
|
+
|
|
95
|
+
### Host Patterns
|
|
96
|
+
|
|
97
|
+
- `host("admin.example.com")` — exact hostname (case-insensitive, port stripped at match time)
|
|
98
|
+
- `host("*.example.com")` — one DNS label (`foo.example.com` yes, `example.com` no, `a.b.example.com` no)
|
|
99
|
+
- `host(/shop\.localhost$/)` — raw RegExp
|
|
110
100
|
|
|
111
101
|
---
|
|
112
102
|
|
|
@@ -114,40 +104,51 @@ const adminRule = apiAuth({
|
|
|
114
104
|
|
|
115
105
|
### Request Context
|
|
116
106
|
|
|
117
|
-
|
|
107
|
+
Default context is an isolated `Map<string, unknown>` per request. For a typed object, pass `createContext` — TypeScript then follows the factory, not a fake generic:
|
|
118
108
|
|
|
119
109
|
```typescript
|
|
120
|
-
|
|
121
|
-
|
|
110
|
+
type Ctx = { user?: { id: string; role: string } }
|
|
111
|
+
|
|
112
|
+
const enrichUser = defineProxy<Ctx>("enrichUser", async (req, ctx) => {
|
|
113
|
+
ctx.user = { id: "usr_1", role: "admin" }
|
|
122
114
|
return next()
|
|
123
115
|
})
|
|
124
116
|
|
|
125
|
-
const checkPermission = defineProxy("checkPermission", (req, ctx) => {
|
|
126
|
-
|
|
127
|
-
if (user?.role !== "admin") {
|
|
117
|
+
const checkPermission = defineProxy<Ctx>("checkPermission", (req, ctx) => {
|
|
118
|
+
if (ctx.user?.role !== "admin") {
|
|
128
119
|
return new Response("Forbidden", { status: 403 })
|
|
129
120
|
}
|
|
130
121
|
return next()
|
|
131
122
|
})
|
|
123
|
+
|
|
124
|
+
export default proxyChain({ createContext: (): Ctx => ({}) }, [enrichUser, checkPermission])
|
|
132
125
|
```
|
|
133
126
|
|
|
127
|
+
Without `createContext`, `ctx` is `ProxyContext` (`Map`). Do not write `proxyChain<{ user: string }>(rules)` — that is a type error.
|
|
128
|
+
|
|
134
129
|
### Request and Response Headers
|
|
135
130
|
|
|
136
|
-
Use `next()` to inject request headers (visible to downstream rules and route handlers) and response headers:
|
|
131
|
+
Use `next()` to inject **request** headers (visible to downstream rules and route handlers) and **response** headers (including `Set-Cookie`):
|
|
137
132
|
|
|
138
133
|
```typescript
|
|
139
134
|
return next({
|
|
140
|
-
// Downstream request headers (NextRequest & server components)
|
|
135
|
+
// Downstream request headers (NextRequest & server components). Always last-write-wins.
|
|
141
136
|
request: {
|
|
142
137
|
"x-user-id": "usr_123",
|
|
143
138
|
},
|
|
144
|
-
// Final outgoing response headers
|
|
139
|
+
// Final outgoing response headers / Set-Cookie
|
|
145
140
|
headers: {
|
|
146
141
|
"cache-control": "no-store",
|
|
142
|
+
"set-cookie": "session=abc; Path=/",
|
|
147
143
|
},
|
|
148
144
|
})
|
|
149
145
|
```
|
|
150
146
|
|
|
147
|
+
- `headerMergeStrategy` / `cookieMergeStrategy` apply to **response** headers and cookies only.
|
|
148
|
+
- Request overrides ignore those strategies (last write wins).
|
|
149
|
+
- Cookies are keyed by **name + domain + path**, so `session; Path=/` and `session; Path=/admin` both survive.
|
|
150
|
+
- Custom merge `return null` removes that response header from the final `Response`.
|
|
151
|
+
|
|
151
152
|
---
|
|
152
153
|
|
|
153
154
|
## API Reference
|
|
@@ -160,22 +161,40 @@ return next({
|
|
|
160
161
|
| `proxyChain(options, rules)` | `(options: ProxyChainOptions, rules: Entry[]) => Handler` | Creates a handler with custom pipeline options. |
|
|
161
162
|
| `defineProxy(name?, fn)` | `(name?: string, fn: ProxyFn) => DefinedProxy` | Defines a reusable proxy rule with scoping capabilities. |
|
|
162
163
|
| `next(options?)` | `(options?: NextOptions) => NextResult` | Returns a continuation token with optional header mutations. |
|
|
163
|
-
| `path(pattern
|
|
164
|
-
| `host(matcher)` | `(matcher: HostMatcher) => RegExp` | Compiles hostname(s) into an anchored `RegExp
|
|
164
|
+
| `path(pattern)` | `(pattern: string \| RegExp) => RegExp` | Compiles a path pattern into a stateless `RegExp`. |
|
|
165
|
+
| `host(matcher)` | `(matcher: HostMatcher) => RegExp` | Compiles hostname(s) into an anchored `RegExp` (`*` = one DNS label). |
|
|
165
166
|
| `createProxyContext()` | `() => ProxyContext` | Creates a new `Map<string, unknown>` context instance. |
|
|
167
|
+
| `isNextResult(value)` | `(value: unknown) => boolean` | Type guard for `next()` continuation tokens. |
|
|
168
|
+
| `RuleTimeoutError` | `Error` | Thrown internally when `ruleTimeoutMs` is exceeded (catchable in `onError`). |
|
|
166
169
|
|
|
167
170
|
### Configuration Options (`ProxyChainOptions`)
|
|
168
171
|
|
|
169
172
|
| Option | Type | Default | Description |
|
|
170
173
|
| :--- | :--- | :--- | :--- |
|
|
171
|
-
| `createContext` | `(req, event) => TContext` | `() => new Map()` | Factory for custom per-request context
|
|
172
|
-
| `headerMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` |
|
|
173
|
-
| `cookieMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` |
|
|
174
|
-
| `ruleTimeoutMs` | `number` | `0` | Wall-clock
|
|
175
|
-
| `onError` | `(err, index, req, ctx) => Response \| void` | `undefined` |
|
|
176
|
-
| `requestHeaderPolicy` | `{ blocked?: string[], allowed?: string[] }` | `{}` |
|
|
177
|
-
| `debug` | `boolean` | `false` |
|
|
178
|
-
| `logger` | `ChainLogger` | `console` | Custom logger
|
|
174
|
+
| `createContext` | `(req, event) => TContext` | `() => new Map()` | Factory for custom per-request context. Required for a non-`Map` `TContext`. |
|
|
175
|
+
| `headerMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` | Conflict strategy for **response** headers only. |
|
|
176
|
+
| `cookieMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` | Conflict strategy for `Set-Cookie` (same name+domain+path). |
|
|
177
|
+
| `ruleTimeoutMs` | `number` | `0` | Wall-clock timeout per rule in ms (`0` disables). Does not abort the rule function; leftover rejections are swallowed. |
|
|
178
|
+
| `onError` | `(err, index, req, ctx) => Response \| NextResult \| void` | `undefined` | Recovery hook. See **Errors** below. |
|
|
179
|
+
| `requestHeaderPolicy` | `{ blocked?: string[], allowed?: string[] }` | `{}` | Blocklist/allowlist for **request** header mutations. |
|
|
180
|
+
| `debug` | `boolean` | `false` | Structured one-line logs per rule. |
|
|
181
|
+
| `logger` | `ChainLogger` | `console` | Custom logger (`debug`, `info`, `warn`, `error`). |
|
|
182
|
+
| `strictOverrideCheck` | `boolean` | `false` | Throw at init if `NextResponse.next()` request overrides look unsupported. |
|
|
183
|
+
| `hostFolderHeader` | `string` | unset | Opt-in: request header name that prefixes rewrites with a physical folder (e.g. `"x-internal-host-folder"`). Off by default. |
|
|
184
|
+
|
|
185
|
+
### Errors (`onError`)
|
|
186
|
+
|
|
187
|
+
| `onError` returns | Behavior |
|
|
188
|
+
| :--- | :--- |
|
|
189
|
+
| `Response` | Stop and return that response (headers/cookies still merged). |
|
|
190
|
+
| `next()` | Continue to the next rule (rule-level errors only). |
|
|
191
|
+
| `undefined` / `void` / `null` | **Fail closed** — `500 Internal Server Error`. |
|
|
192
|
+
| throws | `500 Internal Server Error`. |
|
|
193
|
+
| omitted | Rule throw → `500`. |
|
|
194
|
+
|
|
195
|
+
`ruleIndex` is `0`-based. `-1` means an engine-level error after context creation; only a `Response` is honored (the pipeline cannot continue).
|
|
196
|
+
|
|
197
|
+
A logging-only `onError: (err) => { console.error(err) }` does **not** skip the failure.
|
|
179
198
|
|
|
180
199
|
### Return Value Protocol
|
|
181
200
|
|
|
@@ -183,19 +202,18 @@ A rule (`ProxyFn`) can return:
|
|
|
183
202
|
|
|
184
203
|
| Return Value | Behavior |
|
|
185
204
|
| :--- | :--- |
|
|
186
|
-
| `next({ request?, headers? })` | Continues
|
|
187
|
-
| `undefined` / `void` | Continues
|
|
188
|
-
| `NextResponse.next()` | Continues
|
|
189
|
-
| `NextResponse.rewrite(url)` | Stages a
|
|
190
|
-
| `NextResponse.redirect(url)` | Stops
|
|
191
|
-
| `Response` / `NextResponse.json()` | Stops
|
|
205
|
+
| `next({ request?, headers? })` | Continues. Queues request overrides, response headers, and `Set-Cookie`. |
|
|
206
|
+
| `undefined` / `void` | Continues without mutations. |
|
|
207
|
+
| `NextResponse.next()` | Continues; extracts Next.js request override headers and cookies. |
|
|
208
|
+
| `NextResponse.rewrite(url)` | **Continues**. Stages a rewrite for later rules; the incoming `NextRequest` is not mutated. The rewrite is applied when the chain finishes unless a later rule returns a terminal response. |
|
|
209
|
+
| `NextResponse.redirect(url)` | Stops immediately with the redirect. |
|
|
210
|
+
| `Response` / `NextResponse.json()` | Stops immediately with that response. |
|
|
192
211
|
|
|
193
212
|
---
|
|
194
213
|
|
|
195
214
|
## Links
|
|
196
215
|
|
|
197
216
|
- [GitHub](https://github.com/klnap/next-proxy-chain)
|
|
198
|
-
- [npm](https://www.npmjs.com/package/@klnap/next-proxy-chain?activeTab=code)
|
|
199
217
|
|
|
200
218
|
---
|
|
201
219
|
|