diff --git a/ext/node/polyfills/http.ts b/ext/node/polyfills/http.ts index 3059da3a68..0ef245902d 100644 --- a/ext/node/polyfills/http.ts +++ b/ext/node/polyfills/http.ts @@ -322,6 +322,7 @@ class ClientRequest extends OutgoingMessage { insecureHTTPParser: boolean; useChunkedEncodingByDefault: boolean; path: string; + _req: { requestRid: number; cancelHandleRid: number | null } | undefined; constructor( input: string | URL, @@ -819,7 +820,9 @@ class ClientRequest extends OutgoingMessage { if (rid) { core.tryClose(rid); } - if (this._req.cancelHandleRid !== null) { + + // Request might be closed before we actually made it + if (this._req !== undefined && this._req.cancelHandleRid !== null) { core.tryClose(this._req.cancelHandleRid); } // If we're aborting, we don't care about any more response data. diff --git a/tests/unit_node/http_test.ts b/tests/unit_node/http_test.ts index a053f3a274..71043d9851 100644 --- a/tests/unit_node/http_test.ts +++ b/tests/unit_node/http_test.ts @@ -994,6 +994,15 @@ Deno.test( }, ); +Deno.test( + "[node/http] client destroy before sending request should not error", + () => { + const request = http.request("http://localhost:5929/"); + // Calling this would throw + request.destroy(); + }, +); + Deno.test("[node/http] node:http exports globalAgent", async () => { const http = await import("node:http"); assert(