@klnap/next-proxy-chain 2.0.0 → 3.0.1

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.
@@ -0,0 +1,88 @@
1
+ # Concepts
2
+
3
+ `chain()` composes native handlers. `defineHandler()` defines a reusable configured handler. `handle` contains the handler's native Next.js logic; Next.js owns HTTP responses.
4
+
5
+ ```ts
6
+ import { chain } from "@klnap/next-proxy-chain";
7
+ import { NextResponse } from "next/server";
8
+
9
+ export default chain([
10
+ (request, event) => {
11
+ event.waitUntil(writeAuditLog(request));
12
+ if (request.nextUrl.pathname === "/") {
13
+ return NextResponse.redirect(new URL("/home", request.url));
14
+ }
15
+ },
16
+ {
17
+ name: "security",
18
+ handle: () => {
19
+ const response = NextResponse.next();
20
+ response.headers.set("x-content-type-options", "nosniff");
21
+ return response;
22
+ },
23
+ },
24
+ ]);
25
+ ```
26
+
27
+ ## Execution
28
+
29
+ Handlers execute in order. A `NextResponse.next()` or `undefined` continues. A successful `NextResponse.rewrite()` stages a rewrite and continues. A redirect or terminal `Response` stops the chain. If every handler continues, the chain returns a pass-through response or the final staged rewrite.
30
+
31
+ The original request object is not mutated. When a continued rewrite or native request-header override changes request state, later handlers receive a reconstructed `NextRequest`. Original URL, path, and hostname remain in chain context.
32
+
33
+ ## Matching
34
+
35
+ Next.js `config.matcher` is the outer filter. It decides whether Middleware or Proxy runs at all.
36
+
37
+ Configured-handler `rules.include` and `rules.exclude` are inner filters. They accept paths, host/path objects, strings, and regular expressions. Exclusions take precedence. The optional async `when(request, event, context)` predicate runs after scope matching.
38
+
39
+ ```ts
40
+ {
41
+ name: "admin-auth",
42
+ rules: {
43
+ include: { host: "admin.example.com", path: "/admin/**" },
44
+ exclude: "/admin/login",
45
+ },
46
+ handle: (request) => {
47
+ if (!hasSession(request)) {
48
+ return NextResponse.redirect(new URL("/login", request.url));
49
+ }
50
+ },
51
+ }
52
+ ```
53
+
54
+ Later matching uses the effective request, including prior rewrite paths and request-header replacements. Rewrites do not change the host used for matching; host scopes read the effective `host` header, falling back to `x-forwarded-host`. A prior header replacement of either value affects later host matching.
55
+
56
+ ## Native HTTP composition
57
+
58
+ The chain does not wrap responses in another API. Handlers return `NextResponse` or Web `Response` directly.
59
+
60
+ | Handler returns | Effect |
61
+ | ---------------------------- | ------------------------------------------------------ |
62
+ | `undefined` | Continue without adding HTTP effects. |
63
+ | `NextResponse.next()` | Continue and compose its response headers and cookies. |
64
+ | `NextResponse.rewrite(url)` | Stage the rewrite; continue through later handlers. |
65
+ | `NextResponse.redirect(url)` | Stop and redirect. |
66
+ | Terminal `Response` | Stop and return it. |
67
+
68
+ Request headers passed in `NextResponse.next({ request: { headers } })` replace the forwarded request-header set. Clone `request.headers` to preserve existing values. The engine decodes Next.js's internal override metadata so later handlers see the same effective headers. Request headers do not become response headers.
69
+
70
+ Response headers and cookies from continuing handlers are collected and merged into the final response. The defaults use last-write-wins. Cookies with different name/domain/path identities remain distinct.
71
+
72
+ ## Context
73
+
74
+ The chain creates request-scoped metadata and an execution-scoped `AbortSignal`. `requestId`, `startedAt`, `elapsedMs`, `originalUrl`, `originalPathname`, and `originalHostname` describe the original request. Custom typed state is shared between handlers in one request and isolated across requests.
75
+
76
+ Custom state fields may be `undefined` before initialization. They are not forwarded to route handlers unless a handler explicitly encodes them into request headers.
77
+
78
+ ## Errors and timeouts
79
+
80
+ The handler's `timeout` and `when` predicate share a deadline. Timeout or request cancellation aborts the execution signal and stops the pipeline from waiting; ignored work can continue. A cooperative handler should pass `context.signal` to cancellable work.
81
+
82
+ For ordinary errors, handler-level `onError` wins over chain-level `onError`. `NextResponse.next()` and a successful `NextResponse.rewrite()` continue after that failed handler; any other `Response` terminates. Timeouts, request cancellation, and engine-level failures cannot resume the chain. They accept only a terminal Web `Response` as recovery; a continuing or rewriting recovery is rejected.
83
+
84
+ ## Diagnostics
85
+
86
+ Formatted diagnostics include one outcome per handler. Compact `reached/total` counts include skipped outcomes, because their scope or predicate was evaluated; handlers after a terminal response count only in `total`.
87
+
88
+ `onTrace` receives structured data with request ID, outcome, timing, and handler details. `tracePath: false` omits the original request pathname from the top-level trace and formatted request line; scope details and sanitized rewrite or redirect destination paths remain visible. Destination query values are replaced with `?[query]`. The formatter sanitizes and truncates displayed names and destinations.
package/docs/guides.md ADDED
@@ -0,0 +1,210 @@
1
+ # Guides
2
+
3
+ ## Native matcher configuration
4
+
5
+ Keep the Next.js matcher at the entrypoint. Use `rules` to scope one handler:
6
+
7
+ ```ts
8
+ export const config = { matcher: ["/api/:path*"] };
9
+
10
+ export default chain([
11
+ {
12
+ name: "api-auth",
13
+ rules: {
14
+ include: "/api/**",
15
+ exclude: "/api/public/**",
16
+ when: async (request) => request.headers.has("authorization"),
17
+ },
18
+ handle: (request) => verifyApiRequest(request),
19
+ },
20
+ ]);
21
+ ```
22
+
23
+ Path strings support `*` for one segment and `**` for zero or more segments. Scope objects can combine `host` and `path`.
24
+
25
+ ## Add, update, and remove request headers
26
+
27
+ Next.js treats the supplied `Headers` as a replacement set. Clone the effective request headers to preserve existing values:
28
+
29
+ ```ts
30
+ import { NextResponse } from "next/server";
31
+
32
+ {
33
+ name: "request-metadata",
34
+ handle: (request) => {
35
+ const headers = new Headers(request.headers);
36
+ headers.set("x-user-tier", "free");
37
+ headers.set("x-request-source", "proxy");
38
+ headers.delete("x-untrusted-client-value");
39
+ return NextResponse.next({ request: { headers } });
40
+ },
41
+ }
42
+ ```
43
+
44
+ To deliberately replace the entire set, create a new `Headers` instance and add only the values to forward. Headers omitted from that set are removed downstream. A later handler sees the effective result and can clone it before making another change.
45
+
46
+ ## Forward a request ID
47
+
48
+ The chain generates `context.requestId`, but does not forward it automatically:
49
+
50
+ ```ts
51
+ import { NextResponse } from "next/server";
52
+
53
+ {
54
+ name: "request-id",
55
+ handle: (request, _event, context) => {
56
+ const headers = new Headers(request.headers);
57
+ headers.set("x-request-id", context.requestId);
58
+ return NextResponse.next({ request: { headers } });
59
+ },
60
+ }
61
+ ```
62
+
63
+ This changes request headers seen by downstream handlers and route code. It does not set a client-facing response header.
64
+
65
+ ## Set response headers and cookies
66
+
67
+ Use the native response object:
68
+
69
+ ```ts
70
+ import { NextResponse } from "next/server";
71
+
72
+ {
73
+ name: "security",
74
+ handle: () => {
75
+ const response = NextResponse.next();
76
+ response.headers.set("x-content-type-options", "nosniff");
77
+ response.cookies.set("locale", "en");
78
+ return response;
79
+ },
80
+ }
81
+ ```
82
+
83
+ Response headers and cookies are composed across continued handlers. Last write wins by default.
84
+
85
+ ## Rewrite and continue
86
+
87
+ A successful rewrite is staged. Later handlers receive the rewritten pathname, while `context.originalPathname` retains the original value:
88
+
89
+ ```ts
90
+ import { NextResponse } from "next/server";
91
+
92
+ {
93
+ name: "localized-route",
94
+ rules: { include: "/**" },
95
+ handle: (request) => {
96
+ if (request.nextUrl.pathname.startsWith("/pl/")) return;
97
+ return NextResponse.rewrite(new URL(`/pl${request.nextUrl.pathname}`, request.url));
98
+ },
99
+ }
100
+ ```
101
+
102
+ Internal and external destinations use Next.js's `NextResponse.rewrite()` API. A later redirect or terminal response stops the chain.
103
+
104
+ ## Redirect
105
+
106
+ ```ts
107
+ import { NextResponse } from "next/server";
108
+
109
+ {
110
+ name: "canonical-host",
111
+ handle: (request) => {
112
+ if (request.nextUrl.hostname !== "www.example.com") {
113
+ return NextResponse.redirect(new URL(request.url.replace("://", "://www."), request.url));
114
+ }
115
+ },
116
+ }
117
+ ```
118
+
119
+ Redirects are terminal. Earlier composed response headers and cookies remain on the outgoing response.
120
+
121
+ ## Share typed context
122
+
123
+ ```ts
124
+ type RequestState = { locale?: "en" | "pl" };
125
+
126
+ export default chain<RequestState>([
127
+ {
128
+ name: "detect-locale",
129
+ handle: (request, _event, context) => {
130
+ context.locale = request.headers.get("accept-language")?.startsWith("pl") ? "pl" : "en";
131
+ },
132
+ },
133
+ {
134
+ name: "locale-header",
135
+ handle: (_request, _event, context) => {
136
+ if (!context.locale) return;
137
+ const response = NextResponse.next();
138
+ response.headers.set("content-language", context.locale);
139
+ return response;
140
+ },
141
+ },
142
+ ]);
143
+ ```
144
+
145
+ Custom context properties may be undefined until initialized. The chain isolates custom state between requests.
146
+
147
+ ## Timeout and cancellation
148
+
149
+ ```ts
150
+ {
151
+ name: "remote-settings",
152
+ timeout: 500,
153
+ handle: async (_request, _event, context) => {
154
+ return fetchSettings({ signal: context.signal });
155
+ },
156
+ }
157
+ ```
158
+
159
+ The handler and its `when` predicate share one timeout. Pass `context.signal` into supported APIs. Timeout stops later handlers; ignored work may continue if it does not honor cancellation.
160
+
161
+ ## Error recovery
162
+
163
+ For ordinary failures, return native `NextResponse.next()` to continue:
164
+
165
+ ```ts
166
+ {
167
+ name: "optional-profile",
168
+ onError: () => NextResponse.next(),
169
+ handle: async () => loadOptionalProfile(),
170
+ }
171
+ ```
172
+
173
+ For timeout and request cancellation, recovery must return a terminal Web `Response`:
174
+
175
+ ```ts
176
+ {
177
+ name: "critical-profile",
178
+ onError: () => new Response("Service unavailable", { status: 503 }),
179
+ timeout: 500,
180
+ handle: async (_request, _event, context) => loadProfile({ signal: context.signal }),
181
+ }
182
+ ```
183
+
184
+ Handler-level `onError` takes precedence over chain-level `onError`. An absent recovery response fails closed.
185
+
186
+ ## Diagnostics
187
+
188
+ Enable readable traces with `debug`:
189
+
190
+ ```ts
191
+ export default chain(handlers, { debug: "detailed" });
192
+ ```
193
+
194
+ Set `debug: "compact"` for a short trace. Compact `reached/total` counts include skipped handlers as reached outcomes, but skipped handlers did not execute their `handle` callback. Handlers after a terminal outcome count only in total.
195
+
196
+ Use `onTrace` for structured data:
197
+
198
+ ```ts
199
+ export default chain(handlers, {
200
+ onTrace: (trace) => {
201
+ console.info({
202
+ requestId: trace.requestId,
203
+ outcome: trace.outcome.type,
204
+ handlers: trace.handlers,
205
+ });
206
+ },
207
+ });
208
+ ```
209
+
210
+ `tracePath: false` omits only the original request pathname from the top-level trace and formatted request line. It does not hide paths in scope details or sanitized rewrite and redirect destinations; destination query values appear as `?[query]`. Formatted traces and structured traces omit request and response header values, cookie values, raw query values, request bodies, application context values, and raw errors. Display formatting sanitizes and truncates handler names and destinations.
@@ -0,0 +1,104 @@
1
+ # Security
2
+
3
+ `@klnap/next-proxy-chain` organizes code that runs in Proxy or Middleware. It does not decide what is allowed. Your rules decide that. This page separates package guarantees from application responsibilities.
4
+
5
+ ## Trust boundaries
6
+
7
+ - **Request data is untrusted.** Paths, queries, cookies, headers, and hosts can be set by clients.
8
+ - **Handlers are trusted code.** A handler can set request headers, response headers, cookies, stop the chain, or rewrite a path.
9
+ - **Upstream responses are data.** Relayed response headers pass through except Next.js routing metadata, which is stripped from terminal responses.
10
+
11
+ ## Authentication
12
+
13
+ The package runs your authentication check; it does not perform one. A present cookie does not prove a session. Verify the session or token in trusted server code:
14
+
15
+ ```ts
16
+ const requireSession = defineHandler({
17
+ name: "require-session",
18
+ handle: async (request) => {
19
+ const session = await verifySession(request.cookies.get("session")?.value);
20
+ if (!session) return NextResponse.redirect(new URL("/login", request.url));
21
+ },
22
+ });
23
+ ```
24
+
25
+ `verifySession` is application-owned. Proxy runs before the route, so route handlers must still authorize access to returned data.
26
+
27
+ Server Functions (Server Actions) use POST requests to their route. Excluding that route from `config.matcher` also skips those calls. Enforce authorization inside each Server Function.
28
+
29
+ ## Ordering and early responses
30
+
31
+ A redirect or terminal `Response` stops the chain. Later handlers do not run, so their checks, headers, and cookies are absent.
32
+
33
+ Put universal security headers first. Put authentication before handlers that can answer a request, such as cache or static-response handlers.
34
+
35
+ ## Path matching
36
+
37
+ - Scopes match decoded paths without a trailing slash. `/%61dmin/users` is matched as `/admin/users`.
38
+ - `/api/*` matches one segment; `/api/**` matches all descendants.
39
+ - Malformed percent encoding returns `400 Bad Request` before handlers run.
40
+ - A handler sees rewrites staged by earlier handlers. Verify that the path it protects is the path Next.js serves.
41
+
42
+ ## Host matching
43
+
44
+ The `host` header comes from the client or a proxy and is not trusted by default. Host scopes are routing aids, not access control. Use a platform host allowlist.
45
+
46
+ - Ports and trailing dots are ignored.
47
+ - Host strings compare case-insensitively. Wildcards match one DNS label.
48
+ - If `host` is missing, matching falls back to `x-forwarded-host`. Trust that header only when a proxy you control sets it.
49
+
50
+ ## Request headers
51
+
52
+ `NextResponse.next({ request: { headers } })` uses Next.js's native request-header override mechanism. The supplied `Headers` instance replaces the forwarded header set. Clone `request.headers` to preserve values; omitted values are removed. Later handlers receive the effective replacement.
53
+
54
+ There is no package-level header allowlist or blocklist. Handler code chooses which headers to forward. Validate any client-controlled value before using it for identity, authorization, host routing, or rewrite decisions. A forwarded header is not trusted merely because Proxy set it; clients may reach a route directly.
55
+
56
+ Request overrides remain separate from outgoing response headers. The package reads Next.js's override metadata to reconstruct the request for later handlers. It strips Next.js routing metadata from terminal responses, including error-recovered responses, so transport instructions are not forwarded as ordinary response headers.
57
+
58
+ ## Rewrites
59
+
60
+ Handlers may use native `NextResponse.rewrite()` for internal or external destinations. Validate destinations derived from request data. Do not pass an untrusted redirect or rewrite target through without checking its origin and allowed paths.
61
+
62
+ ## Response headers and cookies
63
+
64
+ - Headers from continuing handlers merge onto the final response. `last-write-wins` is the default.
65
+ - Cookies use name, domain, and path identity. A later cookie with the same identity replaces an earlier one by default.
66
+ - Next.js routing headers are stripped from terminal responses. Native `NextResponse.next()` and `NextResponse.rewrite()` metadata is interpreted only as routing behavior, not copied to the client as ordinary response headers.
67
+
68
+ ## Diagnostics and privacy
69
+
70
+ Debug logs and `onTrace` are disabled unless enabled. Formatted traces and structured traces omit request and response header values, cookie values, request bodies, application context values, and raw errors. Redirect and rewrite query values are redacted.
71
+
72
+ Pathnames can contain personal data. `tracePath: false` omits only the original request pathname from the top-level structured trace and formatted request line. It does not hide paths in handler scope details or sanitized rewrite and redirect destinations. Destination query values appear as `?[query]`. Handler names and scope strings are sanitized and length-limited before display.
73
+
74
+ Treat traces as operational data. Logger callbacks can persist them beyond the request; the package cannot control retention, access, or cross-process ordering.
75
+
76
+ ## Error recovery
77
+
78
+ For ordinary handler errors, handler-level `onError` takes precedence over chain-level `onError`:
79
+
80
+ - `NextResponse.next()` and a successful `NextResponse.rewrite()` continue after the failed handler.
81
+ - A Web `Response` terminates with that response.
82
+ - `undefined`, `void`, `null`, a throw, or an unsupported return fails closed with `500`.
83
+
84
+ Timeout, request-cancellation, and engine-level recovery accept only a terminal Web `Response`. Continuation and `NextResponse.rewrite()` are rejected, so a timed-out gate cannot rewrite a request past later handlers. This is routing correctness, not an authorization guarantee: the application remains responsible for its own access checks. Without timeout recovery, the chain returns `500`, but ignored work may continue. Without cancellation recovery, the chain stops and returns the native `NextResponse.next()` handoff; Next.js may continue downstream routing after a client disconnect. This handoff is not fail-closed.
85
+
86
+ ## Timeouts
87
+
88
+ Handler `timeout` covers its `when` predicate and `handle` together. Timeout or request cancellation aborts the execution-scoped signal and stops the engine from waiting. Cooperative work can stop early; synchronous JavaScript, ignored signals, and side effects cannot be forcibly stopped or undone.
89
+
90
+ Each handler execution gets its own signal. The predicate shares that handler's signal. `event.waitUntil()` work is not supervised by the timeout; pass `context.signal` explicitly when background work should follow the handler lifetime.
91
+
92
+ ## Context
93
+
94
+ Each request gets isolated context. Built-in request metadata is immutable; application properties are mutable. `originalUrl` may contain sensitive query values. Do not log or forward it without redaction. Context values do not enter built-in diagnostics.
95
+
96
+ ## Next.js version notes
97
+
98
+ - Next.js 16 uses `proxy.ts` and the Node.js runtime by default. Proxy does not accept a `runtime` setting.
99
+ - Next.js 15 uses `middleware.ts` and may run on Edge. Edge behavior must be verified separately for the target release.
100
+ - `config.matcher` decides which paths reach Proxy or Middleware. Handler scopes cannot widen that set.
101
+
102
+ ## Reporting a vulnerability
103
+
104
+ Do not open a public issue for a security problem. Use GitHub's private vulnerability reporting from the repository's **Security** tab.
package/llms.txt ADDED
@@ -0,0 +1,17 @@
1
+ # @klnap/next-proxy-chain
2
+
3
+ > Composable proxy and middleware for Next.js.
4
+
5
+ Handler callbacks are positional: use `request`, `event`, and `context` for used parameters; prefix intentionally unused parameters with `_` when later arguments need their positions, and omit unused trailing parameters.
6
+
7
+ The only runtime exports are `chain()` and `defineHandler()`. Configured handlers use `handle`, not `handler`. `undefined` and `NextResponse.next()` continue; successful `NextResponse.rewrite()` stages a rewrite and continues; redirects and terminal `Response` values stop the chain. Use native Next.js and Web response APIs.
8
+
9
+ ## Documentation
10
+
11
+ - [README](README.md): purpose, quick start, canonical usage, compatibility, and documentation discovery.
12
+ - [Concepts](docs/concepts.md): execution order, matching, rewrites, HTTP effects, context, and timeouts.
13
+ - [Guides](docs/guides.md): native matchers, practical handler recipes, request IDs, cancellation, and diagnostics.
14
+ - [API reference](docs/api.md): exports, handler configuration, matching syntax, options, types, and defaults.
15
+ - [Security](docs/security.md): trust boundaries, native request-header replacement, authorization, rewrites, and diagnostics privacy.
16
+
17
+ Read the installed README and relevant supporting pages before integrating. The public declarations are in `dist/index.d.ts` and `dist/index.d.cts`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klnap/next-proxy-chain",
3
- "version": "2.0.0",
3
+ "version": "3.0.1",
4
4
  "description": "Composable proxy and middleware for Next.js.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,7 +35,12 @@
35
35
  "dist/index.js",
36
36
  "README.md",
37
37
  "CHANGELOG.md",
38
- "LICENSE"
38
+ "LICENSE",
39
+ "llms.txt",
40
+ "docs/api.md",
41
+ "docs/concepts.md",
42
+ "docs/guides.md",
43
+ "docs/security.md"
39
44
  ],
40
45
  "exports": {
41
46
  ".": {