Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
ea0c938
fix(types): accept connect-style middleware in `fetchNodeHandler` and…
nitedani Oct 9, 2026
65dfeab
fix(node): pass `next` to middleware round-tripped through `toNodeHan…
nitedani Oct 18, 2026
b750698
fix(node): forward the caller's `next` to round-tripped middleware
nitedani Oct 18, 2026
3cbf4a9
fix(node): return the middleware's promise from the round-tripped han…
nitedani Oct 18, 2026
223e6ee
fix(node): keep a round-tripped error handler an error handler
nitedani Oct 18, 2026
61c9878
fix(node): say what the round-tripped middleware's fallback `next` co…
nitedani Oct 18, 2026
53c0b67
refactor(node): name the round-tripped middleware wrapper
nitedani Oct 18, 2026
2cae6c1
Merge remote-tracking branch 'origin/main' into fix/fetch-node-handle…
nitedani Oct 18, 2026
1ac13e8
fix(node): keep the round-tripped middleware's name
nitedani Oct 18, 2026
46f6be1
fix(node): answer 404 when round-tripped middleware calls `next()` on…
nitedani Oct 18, 2026
b61c0a5
fix(node): answer the error's status when round-tripped middleware ca…
nitedani Oct 18, 2026
730f076
fix(node): return a round-tripped connect or Express app as is
nitedani Oct 18, 2026
7713c7d
Merge main into fix/fetch-node-handler-middleware-type
nitedani-agent Nov 11, 2026
49088a8
fix(node): wrap an Express router like other middleware
nitedani-agent Nov 11, 2026
103b0ac
fix(node): return a three-argument middleware's response once its hea…
nitedani-agent Nov 11, 2026
27d6aa6
fix(node): release the synthetic request when a middleware fails
nitedani-agent Nov 11, 2026
cad3659
fix(node): close the synthetic request when a middleware fails after …
nitedani-agent Nov 11, 2026
8ae6919
fix(node): fail the body when a middleware throws after its head
nitedani-agent Nov 11, 2026
2625c14
fix(node): return an Express app's streaming response once its head i…
nitedani-agent Nov 11, 2026
cf3ae45
fix(node): keep the Transfer-Encoding guards in an Express app
nitedani-agent Nov 11, 2026
b276ef2
Merge remote-tracking branch 'upstream/main' into fix/fetch-node-hand…
nitedani Nov 23, 2026
f6c5f84
fix(node): run an Express app's own `setHeader` and `writeHead`
nitedani Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 34 additions & 4 deletions src/adapters/_node/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import type {
FetchHandler,
NodeHttpHandler,
NodeHTTPMiddleware,
NodeServerRequest,
NodeServerResponse,
ServerRequest,
} from "../../types.ts";
import type { TrustProxyOption } from "../../_trust-proxy.ts";
import { fetchNodeHandler } from "../node.ts";
import { NodeRequest } from "./request.ts";
import { handleSendError, sendNodeResponse } from "./send.ts";
import { handleSendError, sendErrorResponse, sendNodeResponse } from "./send.ts";
import { hasAmbiguousPath } from "./url.ts";

export type AdapterMeta = {
Expand Down Expand Up @@ -72,16 +73,45 @@ function send(nodeRes: NodeServerResponse, webRes: Response): Promise<void> {
*
* @experimental Behavior might be unstable and won't work in Bun and Deno currently (tracker: https://github.com/h3js/srvx/issues/132)
*/
export function toFetchHandler(handler: NodeHttpHandler & AdapterMeta): FetchHandler & AdapterMeta {
export function toFetchHandler(
handler: (NodeHttpHandler | NodeHTTPMiddleware) & AdapterMeta,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
): FetchHandler & AdapterMeta {
if (handler.__fetchHandler) {
return handler.__fetchHandler;
}

function convertedNodeHandler(req: ServerRequest): Promise<Response> {
return fetchNodeHandler(handler as NodeHttpHandler, req);
return fetchNodeHandler(handler, req);
}

(convertedNodeHandler as AdapterMeta).__nodeHandler = handler as NodeHttpHandler;
// A connect or Express app (`app.listen`) comes back as is, since its own final handler ends the stack; other middleware, an Express router included, gets the caller's `next`, else one where `next()` answers 404 and `next(err)` 500.
function nodeMiddleware(
nodeReq: NodeServerRequest,
nodeRes: NodeServerResponse,
next?: (error?: Error) => void,
) {
return (handler as NodeHTTPMiddleware)(
nodeReq as any,
nodeRes as any,
next ||
((error) => {
if (error) {
sendErrorResponse(nodeRes, error);
} else {
if (!nodeRes.headersSent) {
nodeRes.statusCode = 404;
}
nodeRes.end();
}
}),
) as void | Promise<void>;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
assignFnName(nodeMiddleware, handler, "");

(convertedNodeHandler as AdapterMeta).__nodeHandler =
handler.length === 3 && typeof (handler as { listen?: unknown }).listen !== "function"
? nodeMiddleware
: (handler as NodeHttpHandler);
assignFnName(convertedNodeHandler, handler, " (converted to Web handler)");

return convertedNodeHandler;
Expand Down
48 changes: 31 additions & 17 deletions src/adapters/_node/web/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { WebServerResponse } from "./response.ts";
* @experimental Behavior might be unstable.
*/
export async function fetchNodeHandler(
handler: NodeHttpHandler,
handler: NodeHttpHandler | NodeHTTPMiddleware,
req: ServerRequest,
): Promise<Response> {
// Direct pass through if coming from a Node server handler
Expand All @@ -43,28 +43,42 @@ export async function fetchNodeHandler(
// A plain `(req, res)` handler keeps its original 2-arg invocation.
if (handler.length > 2) {
await new Promise<void>((resolve, reject) => {
nodeRes.once("finish", () => resolve());
nodeRes.once("close", () => resolve());
// Past the head, an error can't change the status, so it fails the body and closes the request.
const fail = (error: Error) => {
if (!nodeRes.headersSent) {
return reject(error);
}
nodeReq.destroy();
nodeRes.destroy(error);
};
// Settle on the head, as `toWebResponse()` does, so a streaming middleware is returned before it ends.
nodeRes.waitForResponseHead().then(resolve, reject);
nodeRes.once("error", (error) => reject(error));
Promise.resolve(
(handler as NodeHTTPMiddleware)(nodeReq as any, nodeRes as any, (error) => {
if (error) {
return reject(error);
}
// `next()` with no downstream handler: finalize the response so
// `toWebResponse()` can settle instead of waiting forever.
if (!nodeRes.writableEnded) {
nodeRes.end();
}
resolve();
}),
).catch((error) => reject(error));
// The executor turns a synchronous throw into a rejection, so it reaches `fail` too.
new Promise((settle) =>
settle(
(handler as NodeHTTPMiddleware)(nodeReq as any, nodeRes as any, (error) => {
if (error) {
return fail(error);
}
// `next()` with no downstream handler: finalize the response so
// `toWebResponse()` can settle instead of waiting forever.
if (!nodeRes.writableEnded) {
nodeRes.end();
}
resolve();
}),
),
).catch(fail);
});
} else {
await handler(nodeReq as any, nodeRes as any);
await (handler as NodeHttpHandler)(nodeReq as any, nodeRes as any);
}
return await nodeRes.toWebResponse();
} catch (error: any) {
// The 500 below replaces this response, so stop reading the request body and close both.
nodeReq.destroy();
nodeRes.destroy();
// Client aborts / premature socket closes are routine (the client is already
// gone), so don't log them as errors. See https://github.com/h3js/srvx/issues/208
const aborted =
Expand Down
15 changes: 12 additions & 3 deletions src/adapters/_node/web/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ export class WebServerResponse extends ServerResponse {
});

// Express can override prototype so we have to bind methods
// (the header writers too: they strip `Transfer-Encoding`, and `writeHead` releases `waitForResponseHead()`)
this.writeHead = this.writeHead.bind(this);
this.setHeader = this.setHeader.bind(this);
this.waitToFinish = this.waitToFinish.bind(this);
this.waitForResponseHead = this.waitForResponseHead.bind(this);
this.toWebResponse = this.toWebResponse.bind(this);
Expand All @@ -108,10 +111,13 @@ export class WebServerResponse extends ServerResponse {
// so this is where `waitForResponseHead()` is released and streaming/SSE
// responses can be handed back before `end()`. See issue #248.
override writeHead(statusCode: number, statusMessage?: any, headers?: any): this {
// Express swaps the prototype for `app.response`, whose `writeHead` may be the app's own.
const writeHead =
this instanceof WebServerResponse ? super.writeHead : Object.getPrototypeOf(this).writeHead;
const result =
typeof statusMessage === "string"
? super.writeHead(statusCode, statusMessage, stripTransferEncoding(headers))
: super.writeHead(statusCode, stripTransferEncoding(headers ?? statusMessage));
? writeHead.call(this, statusCode, statusMessage, stripTransferEncoding(headers))
: writeHead.call(this, statusCode, stripTransferEncoding(headers ?? statusMessage));
this.#onHeadersSent?.();
return result;
}
Expand All @@ -120,7 +126,10 @@ export class WebServerResponse extends ServerResponse {
if (typeof name === "string" && name.toLowerCase() === "transfer-encoding") {
return this;
}
return super.setHeader(name, value);
// Express swaps the prototype for `app.response`, whose `setHeader` may be the app's own.
return this instanceof WebServerResponse
? super.setHeader(name, value)
: Object.getPrototypeOf(this).setHeader.call(this, name, value);
}

override appendHeader(name: string, value: string | readonly string[]): this {
Expand Down
Loading
Loading