From 7fcae1d8951d91626c6b778d6e4ac1c6319579e3 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Thu, 30 Oct 2025 14:59:12 +0100 Subject: [PATCH] fix: HEAD when only GET is registered in .route() (#3587) --- packages/fresh/src/app_test.tsx | 21 +++++++++++++++++++++ packages/fresh/src/fs_routes_test.tsx | 4 ++-- packages/fresh/src/segments.ts | 15 +++++++++++---- 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/fresh/src/app_test.tsx b/packages/fresh/src/app_test.tsx index 87fe15cb..5087586a 100644 --- a/packages/fresh/src/app_test.tsx +++ b/packages/fresh/src/app_test.tsx @@ -788,6 +788,27 @@ Deno.test("App support HEAD if only GET is registered", async () => { expect(res.status).toEqual(200); }); +Deno.test( + "App support HEAD in .route() when only GET is registered", + async () => { + const app = new App() + .route("/", { + handler: { + GET() { + return { data: {} }; + }, + }, + component: () =>

foo

, + }); + + const server = new FakeServer(app.handler()); + + const res = await server.head("/"); + expect(res.body).toEqual(null); + expect(res.status).toEqual(200); + }, +); + Deno.test("App - .appWrapper()", async () => { const app = new App() .appWrapper(({ Component }) => ( diff --git a/packages/fresh/src/fs_routes_test.tsx b/packages/fresh/src/fs_routes_test.tsx index c9f980f0..1dc22123 100644 --- a/packages/fresh/src/fs_routes_test.tsx +++ b/packages/fresh/src/fs_routes_test.tsx @@ -93,8 +93,8 @@ Deno.test("fsRoutes - registers HTTP methods on router", async () => { await res.body?.cancel(); if (method === "GET" && other === "HEAD") { - // When only a HEAD route is registered it should return 404 - expect(res.status).toEqual(404); + // GET route + HEAD request should return 200 + expect(res.status).toEqual(200); } else { expect(res.status).toEqual(405); } diff --git a/packages/fresh/src/segments.ts b/packages/fresh/src/segments.ts index 5ec70cf5..07ae745a 100644 --- a/packages/fresh/src/segments.ts +++ b/packages/fresh/src/segments.ts @@ -4,7 +4,7 @@ import { type Method, patternToSegments } from "./router.ts"; import type { LayoutConfig, Route } from "./types.ts"; import { type Context, getInternals } from "./context.ts"; import { recordSpanError, tracer } from "./otel.ts"; -import { isHandlerByMethod } from "./handlers.ts"; +import { type HandlerFn, isHandlerByMethod } from "./handlers.ts"; import { type AsyncAnyComponent, type PageProps, @@ -167,9 +167,16 @@ export async function renderRoute( attributes: { "fresh.span_type": "fs_routes/handler" }, }, async (span) => { try { - const fn = isHandlerByMethod(handlers) - ? handlers[method] ?? null - : handlers; + let fn: HandlerFn | null = null; + if (isHandlerByMethod(handlers)) { + if (handlers[method] !== undefined) { + fn = handlers[method]; + } else if (method === "HEAD" && handlers.GET !== undefined) { + fn = handlers.GET; + } + } else { + fn = handlers; + } if (fn === null) return await ctx.next();