Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions .changeset/head-declining-get.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"filesystem-routing": patch
---

`createAPIHandler` treats a `HEAD` request whose `GET` handler declines (returns `undefined`) the same as the `GET` itself: a page falls through to the chain and a handler-only route answers 404. It previously threw "did not return a response", which surfaced as a 500 to link checkers, monitors and crawlers that send `HEAD`.
4 changes: 2 additions & 2 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ function toResponse(result: unknown): Response {
* or no handler for the method) advance the chain; `HEAD` falls back to the
* `GET` handler; matched params are written to `event.params` before the
* handler runs. A handler returning `undefined` declines the request —
* allowed for `GET` only (anything else throws): a page module falls
* allowed for `GET` and `HEAD` only (anything else throws): a page module falls
* through to the chain (its component renders instead), a handler-only
* module answers 404.
*/
Expand Down Expand Up @@ -204,7 +204,7 @@ export function createAPIHandler(
const result = await fn(event);

if (result !== undefined) return toResponse(result);
if (request.method !== "GET") {
if (request.method !== "GET" && request.method !== "HEAD") {
throw new Error(
`API handler for ${request.method} "${request.url}" did not return a response.`
);
Expand Down
16 changes: 16 additions & 0 deletions test/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,22 @@ describe("createAPIHandler", () => {
expect(notFound.status).toBe(404);
});

it("falls through on HEAD when the GET answering it declines", async () => {
const asPage = [
{ path: "/about", page: true, $component: {}, $GET: ref({ GET: () => undefined }) }
];
const head = await dispatch(asPage, new Request("http://test/about", { method: "HEAD" }))
.response;
expect(await head.text()).toBe("rendered");

const handlerOnly = [{ path: "/api/thing", $GET: ref({ GET: () => undefined }) }];
const notFound = await dispatch(
handlerOnly,
new Request("http://test/api/thing", { method: "HEAD" })
).response;
expect(notFound.status).toBe(404);
});

it("strips the configured base before matching", async () => {
const routes = [{ path: "/api/thing", $GET: ref({ GET: () => new Response("ok") }) }];
const { response } = dispatch(routes, new Request("http://test/app/api/thing"), {
Expand Down
Loading