A type-safe, composable proxy chain for Next.js.
Compose multiple proxy handlers into a single, ordered execution chain.
Handlers are ordinary ProxyHandler functions. They use native NextResponse values for HTTP effects:
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const rewriteLegacy: ProxyHandler = (request) => {
if (request.nextUrl.pathname !== "/legacy") return;
return NextResponse.rewrite(new URL("/new", request.url));
};
const addRequestId: ProxyHandler = (_request, _event, context) => {
const response = NextResponse.next();
response.headers.set("x-request-id", context.requestId);
return response;
};
export default chain([rewriteLegacy, addRequestId]);
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};- Handlers are plain functions typed with
ProxyHandler. The package adds no response wrapper and no handler-definition helper. - Execution order is the array order. Each handler sees the request as earlier handlers left it.
- Per-handler
rules,timeout,debug, andonErrorare set where the handler is composed, not inside it. - Each request gets typed, isolated context, a request ID, and an abort signal.
- Diagnostics omit header values, cookie values, query values, application context, and raw errors.
bun add @klnap/next-proxy-chain
# or
npm install @klnap/next-proxy-chainThe package declares next ^16.0.0 as a peer dependency and requires Node.js 20.9 or newer. See Compatibility.
Handlers run in array order. Each handler returns one of these values:
| Handler returns | Chain behavior |
|---|---|
undefined, null, or no value |
Continue to the next handler. Native Next.js handlers may return null. |
NextResponse.next() |
Compose response headers and cookies, then continue. |
Successful NextResponse.rewrite(url) |
Stage the rewrite and continue. Later handlers see the rewritten path. |
NextResponse.redirect(url) |
Stop and redirect. |
Terminal Web Response |
Stop and return the response. |
Only Next.js NextResponse routing responses are read as continuation or rewrite instructions. A plain Response stays terminal, including one with Next.js routing headers. A rewrite with a non-success status is also terminal. Native Next.js routes a NextResponse.rewrite() with a custom non-success status from its rewrite header. The chain strips that routing header from the terminal response, so it cannot route unexpectedly.
If every handler continues, the chain returns a pass-through response or the final staged rewrite. The original request is not mutated. A terminal redirect stops the chain:
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const redirectOldPath: ProxyHandler = (request) => {
if (request.nextUrl.pathname === "/old") {
return NextResponse.redirect(new URL("/new", request.url), 308);
}
};
export default chain([redirectOldPath]);NextResponse.next({ request: { headers } }) replaces the forwarded request-header set. Clone the active headers to preserve values. Delete a header from the Headers object to remove it downstream. Later handlers see the effective replacement:
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const addRequestMetadata: ProxyHandler = (request, _event, context) => {
const headers = new Headers(request.headers);
headers.set("x-request-id", context.requestId);
headers.set("x-request-source", "proxy");
headers.delete("x-untrusted-client-value");
return NextResponse.next({ request: { headers } });
};
export default chain([addRequestMetadata]);The chain creates context.requestId but does not forward it automatically; the example forwards it to later handlers and route code. To replace the whole set, create a new Headers and add only the values to forward. Request headers stay separate from client-facing response headers.
The chain does not read or buffer request bodies. An unconsumed body stays available downstream. Clone the request before reading when several handlers need the body.
Use the native response object. Headers and cookies from continuing handlers merge into the final response:
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const addSecurityHeaders: ProxyHandler = () => {
const response = NextResponse.next();
response.headers.set("x-content-type-options", "nosniff");
response.cookies.set("site-preference", "compact", { path: "/", sameSite: "lax" });
return response;
};
export default chain([addSecurityHeaders]);Conflicts resolve with headerMergeStrategy and cookieMergeStrategy. Each defaults to "last-write-wins" and also accepts "first-write-wins" or a custom resolver. A resolver may return null to remove a header or cookie identity.
Cookie identity includes name, domain, effective path, and partitioned status. An omitted or invalid Path uses the default path derived from the original request URL. Domain comparison ignores ASCII case and one leading dot. Paths are case-sensitive.
Outgoing cookies are instructions for the browser. They do not change the current request's cookies.
ProxyHandler<TContext> and chain<TContext>() add typed application state to the request-scoped context:
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
type RequestState = { routeGroup?: "api" | "page" };
const classifyRequest: ProxyHandler<RequestState> = (request, _event, context) => {
context.routeGroup = request.nextUrl.pathname.startsWith("/api/") ? "api" : "page";
};
const addRouteGroupHeader: ProxyHandler<RequestState> = (_request, _event, context) => {
if (!context.routeGroup) return;
const response = NextResponse.next();
response.headers.set("x-route-group", context.routeGroup);
return response;
};
export default chain<RequestState>([classifyRequest, addRouteGroupHeader]);ProxyContext<TContext> contains:
requestId: generated request identifier.startedAtandelapsedMs: request start time and live elapsed duration.originalUrl,originalPathname, andoriginalHostname: initial request metadata. These do not change when a rewrite is staged.signal: execution-scopedAbortSignal.- Optional mutable application fields from
TContext.
Application fields are optional until initialized. State is shared between handlers for one request and isolated between requests. The chain does not forward context to route handlers automatically.
Handlers receive the native NextRequest and NextFetchEvent, then ProxyContext. Declare only the parameters a handler uses. The chain passes Next.js's original event through unchanged.
A successful NextResponse.rewrite() is staged. Later handlers see the rewritten path, while context.originalPathname keeps the initial path. Internal and external destinations both use native NextResponse.rewrite():
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const rewriteLegacy: ProxyHandler = (request) => {
if (request.nextUrl.pathname !== "/legacy") return;
return NextResponse.rewrite(new URL("/new", request.url));
};
const setRouteHeader: ProxyHandler = () => {
const response = NextResponse.next();
response.headers.set("x-route-version", "new");
return response;
};
export default chain([
rewriteLegacy,
{ name: "new-route", handle: setRouteHeader, rules: { include: "/new" } },
]);Next.js config.matcher is the outer filter. It decides whether the proxy.ts entrypoint runs. Handler rules run only after that invocation and cannot widen the native matcher. Keep config.matcher in the entrypoint:
export const config = { matcher: ["/api/:path*"] };includeandexcludeaccept a path string, aRegExp, or an object withpathand/orhost. Alternatives in one list use OR semantics. A matchingexcludetakes precedence.- Path strings:
*matches one path segment and**matches zero or more segments./api/**matches/api,/api/a, and/api/a/b. - Paths are matched decoded and without a trailing slash.
/%61dmin/usersmatches as/admin/users. Malformed percent encoding returns400 Bad Requestbefore any handler runs. - Host scopes use the effective
hostheader, falling back tox-forwarded-hostwhenhostis missing. Comparison ignores case, ports, and trailing dots. A wildcard matches one DNS label. - An optional
when(request, event, context)predicate may return a boolean orPromise<boolean>. It runs after scope matching and shares the handler's timeout. - Matching uses the active request at each handler's turn. Continued rewrites and request-header replacements affect later matching. Host scopes keep the original host after a rewrite.
Scopes select when a handler runs. They do not authenticate users or authorize requests. Keep authorization checks in application code.
chain(entries, options) returns (request, event) => Promise<NextResponse | Response>, which is the default export of proxy.ts. Entries are an array of ProxyHandler functions and configured entries, run sequentially in array order.
Configured entries inline name, handle, and their options directly in chain(). Both name and handle are required, and name must be non-empty. TypeScript infers the options and callbacks from chain():
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const addRequestId: ProxyHandler = (_request, _event, context) => {
const response = NextResponse.next();
response.headers.set("x-request-id", context.requestId);
return response;
};
export default chain([
{
name: "api-request-id",
handle: addRequestId,
rules: {
include: "/api/**",
exclude: "/api/health",
when: (request) => request.method === "GET",
},
timeout: 500,
debug: "compact",
onError: () => new Response("Temporarily unavailable", { status: 503 }),
},
]);Reusable functions can stay unconfigured. To type a stored list that mixes functions and configured entries, use ChainEntry<TContext>.
Configured entries accept these options:
| Entry option | Meaning |
|---|---|
name |
Required, non-empty identifier for the entry. Shown in diagnostics after sanitization. |
handle |
Required ProxyHandler function. |
rules |
include, exclude, and an optional when predicate. See Scopes and matching. |
timeout |
Per-handler deadline in milliseconds. Takes precedence over the chain timeout. |
debug |
Diagnostic level for this entry. |
onError |
Error recovery for this entry. Takes precedence over chain-level onError. |
chain(entries, options) accepts these chain options:
| Option | Default | Meaning |
|---|---|---|
timeout |
0 |
Default per-handler deadline in milliseconds. 0 disables timeouts. |
debug |
false |
Disable logs or select true, "compact", "detailed", or "verbose". |
logger |
Console logger | Logger with debug, info, warn, and error methods. |
onError |
None | Chain-level error recovery. |
onTrace |
None | Receives structured request traces. |
tracePath |
true |
Include the original path in the top-level trace and formatted request line. |
headerMergeStrategy |
"last-write-wins" |
Resolve response-header conflicts. |
cookieMergeStrategy |
"last-write-wins" |
Resolve cookie conflicts. |
strictOverrideCheck |
false |
Throw at chain creation if Next.js request-header override metadata cannot be verified. |
The package exports the types ProxyHandler, ProxyContext, RequestMetadata, ChainEntry, ChainOptions, ChainLogger, HandlerWhen, OnErrorHandler, OnErrorResult, the path and host matcher types, and the structured diagnostic and tracing types. The only runtime export is chain.
A handler's timeout is its execution budget in milliseconds. 0 disables it, and a handler value takes precedence over the chain value. The when predicate shares that budget. On timeout, the chain aborts the execution signal and stops waiting. It cannot stop JavaScript that ignores the signal, so pass context.signal to cancellable work such as fetch. event.waitUntil() work is not supervised by the timeout.
Handler-level onError takes precedence over chain-level recovery. Accepted recovery and the outcome without it, by failure type:
| Failure | Recovery accepted | Without recovery |
|---|---|---|
| Ordinary handler error | NextResponse.next() or a successful rewrite continues after the failed handler. Another Response is terminal. |
Fails closed with 500. |
| Timeout | Terminal Web Response only. Continuation and rewrite are rejected. |
Returns 500. Ignored work may continue. |
| Request cancellation | Terminal Web Response only. Continuation and rewrite are rejected. |
Stops the chain and hands a native NextResponse.next() to Next.js. Not fail-closed. |
| Engine failure | Terminal Web Response only. Continuation and rewrite are rejected. |
Returns 500. |
A recovery value of undefined, void, null, or an unsupported return fails closed with 500. Continuation or rewrite recovery for a timeout, cancellation, or engine failure would resume routing past the failed step, so it is rejected.
Logs and traces are disabled by default. Set debug for readable output, with one outcome per handler. Compact reached counts include handlers skipped because their scope or predicate was evaluated. onTrace receives the request ID, outcome, timing, and handler details.
Built-in diagnostics omit request and response header values, cookie values, request bodies, query values, application context values, and raw errors. Redirect and rewrite query values appear as ?[query]. Handler names and scope strings are sanitized and length-limited before display.
Pathnames can contain personal data. tracePath: false removes only the original request pathname from the top-level structured trace and the formatted request line. It does not hide paths in matched scope details or in sanitized rewrite and redirect destinations.
Treat traces as operational data. Logger callbacks can persist them beyond the request. originalUrl can contain sensitive query values, so do not log it without redaction.
The strict override probe checks whether NextResponse.next() encodes Next.js request-header override metadata. It runs once per module instance. A failed probe logs a warning by default. strictOverrideCheck: true throws during chain construction instead. The package does not emulate unsupported Next.js behavior.
@klnap/next-proxy-chain composes code that runs in Next.js Proxy. It does not authenticate users or authorize requests. Report vulnerabilities through the security policy, not in a public issue.
- Request data is untrusted. Paths, queries, cookies, headers, and hosts can be set by clients.
- Handlers are trusted code. A handler can set headers and cookies, stop the chain, or rewrite a path.
- Upstream responses are data. Relayed headers pass through, except Next.js routing metadata.
A cookie's presence is not proof of a session. Verify identity and permissions in application server logic. Proxy runs before a route and is not the only security boundary. Route Handlers, Server Actions, and data access must authorize protected operations themselves.
Server Functions (Server Actions) send POST requests to their route. Excluding that route from config.matcher also skips those calls. Enforce authorization inside each Server Function.
A redirect or terminal Response stops the chain. Later handlers do not run, so their checks, headers, and cookies are absent. Put universal security headers first. Put authentication before handlers that can answer a request, such as cache or static-response handlers.
Path matching rules are described in Scopes and matching. A handler sees rewrites staged by earlier handlers. Verify that the path a handler protects is the path Next.js serves.
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. Trust x-forwarded-host only when a proxy you control sets it.
There is no package-level header allowlist or blocklist. Handler code chooses what to forward. Validate client-controlled values before using them for identity, authorization, host routing, or rewrite decisions. Clients may reach a route directly, so a forwarded header is not trusted merely because Proxy set it.
In the verified Next.js 16.4.6 production fixture, an external rewrite destination received explicitly forwarded request headers and Proxy response headers as destination request headers. The chain matched a native Proxy for synthetic Authorization, Cookie, API-key, replacement, and deletion canaries. Treat an external rewrite host as a recipient of those values. Delete credentials from the outgoing request override when the destination must not receive them. The chain does not impose an external-host credential policy.
Continuing headers merge onto the final response, and cookies follow the identity in Response headers and cookies. Routing metadata is stripped from terminal and recovered responses. The package does not treat client-supplied control-looking headers as trusted routing instructions.
Continuing recovery skips the handler that failed. It is an explicit fail-open choice for that handler. Use it only for optional work, and avoid chain-level continuation when security gates are present. Return a terminal 401, 403, or 503 when a security handler cannot complete safely.
A timed-out gate cannot rewrite a request past later handlers. This is a routing guarantee, not an authorization guarantee.
Validate every destination derived from request data. Do not pass an untrusted redirect or rewrite target through without checking its origin and allowed paths.
- Peer dependency:
next^16.0.0. Use a security-patched Next.js release. Node.js 20.9 or newer is required. - Proxy is Node-only. Next.js 16 Proxy does not accept a
runtimesetting. - Verified in CI: Next.js 16.4.6 on Node.js 24, with the runtime fixture. The packed consumer is smoke-tested on Node.js 20.9, 22, 24, and 26.
- Unverified: Next.js 15 Middleware and other runtimes. Other Next.js versions are not claimed.
- Modules: ESM and CommonJS builds, with TypeScript declarations for both.
In a tested Next.js 16.4.6 consumer, TypeScript NodeNext reports a next/server subpath resolution error with and without this package. Native Next.js-only consumers show the same issue, but Bundler resolution works. If your project requires NodeNext, map the subpath to the installed declaration file:
{
"compilerOptions": {
"paths": {
"next/server": ["./node_modules/next/server.d.ts"]
}
}
}Version 5.0.0 is a breaking major release. Replace handler-definition wrappers with ordinary functions, and move execution settings into chain().
Before:
import { chain, defineHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const addHeader = defineHandler({
name: "add-header",
rules: { include: "/admin/**" },
timeout: 500,
handle: () => {
const response = NextResponse.next();
response.headers.set("x-example", "enabled");
return response;
},
});
export default chain([addHeader]);After:
import { chain, type ProxyHandler } from "@klnap/next-proxy-chain";
import { NextResponse } from "next/server";
const addHeader: ProxyHandler = () => {
const response = NextResponse.next();
response.headers.set("x-example", "enabled");
return response;
};
export default chain([
{ name: "add-header", handle: addHeader, rules: { include: "/admin/**" }, timeout: 500 },
]);Move name, rules, timeout, debug, and onError to the composition entry. Remove the HandlerConfig annotation or import, because chain() infers the configuration.
Renamed public types:
- Replace
NativeProxywithProxyHandler, an executable(request, event, context)function type. - Replace
HandlerContext<T>withProxyContext<T>. ChainEntry<T>remains available for typed arrays of functions and configured entries.
The only runtime export is chain.
- CHANGELOG
- Security policy
- Contributing
- Examples, each type-checked and tested
- Next.js Proxy documentation
MIT. See LICENSE.