diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 4cf8cd61c0..bbcace4a83 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -8003,6 +8003,11 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp callframe: *JSC.CallFrame, ) bun.JSError!JSC.JSValue { JSC.markBinding(@src()); + + if (this.config.onRequest == .zero) { + return JSPromise.rejectedPromiseValue(ctx, ZigString.init("fetch() requires the server to have a fetch handler").toErrorInstance(ctx)); + } + const arguments = callframe.arguments_old(2).slice(); if (arguments.len == 0) { const fetch_error = WebCore.Fetch.fetch_error_no_args; @@ -8088,6 +8093,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp var request = Request.new(existing_request); + bun.assert(this.config.onRequest != .zero); // confirmed above const response_value = this.config.onRequest.call( this.globalThis, this.jsValueAssertAlive(), diff --git a/test/js/bun/http/bun-serve-routes.test.ts b/test/js/bun/http/bun-serve-routes.test.ts index 1d82bc02d2..e4b6333e60 100644 --- a/test/js/bun/http/bun-serve-routes.test.ts +++ b/test/js/bun/http/bun-serve-routes.test.ts @@ -541,3 +541,12 @@ it("throws a validation error when routes object is undefined and fetch is not s Learn more at https://bun.sh/docs/api/http" `); }); + +it("don't crash on server.fetch()", async () => { + await using server = Bun.serve({ + port: 0, + routes: { "/test": () => new Response("test") }, + }); + + expect(server.fetch("/test")).rejects.toThrow("fetch() requires the server to have a fetch handler"); +});