Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: undefined HTTP method handlers not responding with 405 #1041

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 16 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
7 changes: 7 additions & 0 deletions packages/start/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import { MatchRoute, Method, Route } from "./types";
// @ts-ignore
var api = $API_ROUTES;

// used by the compiled configuration of routes
// @ts-ignore
function methodNotAllowed() {
return new Response(null, { status: 405 });
}

// This is copied from https://github.com/solidjs/solid-router/blob/main/src/utils.ts
function expandOptionals(pattern: string): string[] {
let match = /(\/?\:[^\/]+)\?/.exec(pattern);
Expand Down Expand Up @@ -95,3 +101,4 @@ export function isApiRequest(request: Request) {

export * from "../server/responses";
export type { APIEvent } from "./types";

10 changes: 5 additions & 5 deletions packages/start/entry-server/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { composeMiddleware, createHandler, default as StartServer } from "./StartServer";
export { default as StartServer, composeMiddleware, createHandler } from "./StartServer";
export type { Middleware, MiddlewareFn, MiddlewareInput } from "./StartServer";

import { JSX } from "solid-js";
Expand All @@ -21,8 +21,8 @@ export const render = (
}
) =>
composeMiddleware([
apiRoutes,
inlineServerFunctions,
apiRoutes,
import.meta.env.START_SSR === "async"
Comment on lines 23 to +25
Copy link
Contributor Author

@edivados edivados Sep 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without changing the order, requests for server functions will be mistakenly handled by wildcard routes (like 404) that now have a handler for all methods.

This can be reproduced in the latest version 0.3.5 by adding a POST method handler to the [...404] page. It will break server functions.

? _renderAsync(fn, options)
: import.meta.env.START_SSR === "streaming"
Expand All @@ -37,7 +37,7 @@ export const renderAsync = (
nonce?: string;
renderId?: string;
}
) => composeMiddleware([apiRoutes, inlineServerFunctions, _renderAsync(fn, options)]);
) => composeMiddleware([inlineServerFunctions, apiRoutes, _renderAsync(fn, options)]);

export const renderStream = (
fn: (context: PageEvent) => JSX.Element,
Expand All @@ -46,7 +46,7 @@ export const renderStream = (
nonce?: string;
renderId?: string;
}
) => composeMiddleware([apiRoutes, inlineServerFunctions, _renderStream(fn, options)]);
) => composeMiddleware([inlineServerFunctions, apiRoutes, _renderStream(fn, options)]);

export const renderSync = (
fn: (context: PageEvent) => JSX.Element,
Expand All @@ -55,4 +55,4 @@ export const renderSync = (
nonce?: string;
renderId?: string;
}
) => composeMiddleware([apiRoutes, inlineServerFunctions, _renderSync(fn, options)]);
) => composeMiddleware([inlineServerFunctions, apiRoutes, _renderSync(fn, options)]);
12 changes: 7 additions & 5 deletions packages/start/fs-router/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -392,11 +392,13 @@ export function stringifyAPIRoutes(
.map(
i =>
`{\n${[
...API_METHODS.filter(j => i.apiPath?.[j]).map(
v =>
i.apiPath != null &&
`${v}: ${jsFile.addNamedImport(v, path.posix.resolve(i.apiPath[v]))}`
),
...API_METHODS.map(v => {
if (i.componentPath && v === "GET")
return undefined;
else if (i.apiPath?.[v])
return `${v}: ${jsFile.addNamedImport(v, path.posix.resolve(i.apiPath[v]))}`;
return `${v}: methodNotAllowed`;
}),
i.componentPath ? `GET: "skip"` : undefined,
`path: ${JSON.stringify(i.path)}`
]
Expand Down
14 changes: 7 additions & 7 deletions packages/start/server/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { renderToStream, renderToString, renderToStringAsync } from "solid-js/we
import { apiRoutes } from "../api/middleware";
import { inlineServerFunctions } from "../server/middleware";
import { redirect } from "../server/responses";
import { FetchEvent, FETCH_EVENT, PageEvent } from "../server/types";
import { FETCH_EVENT, FetchEvent, PageEvent } from "../server/types";

export function renderSync(
fn: (context: PageEvent) => JSX.Element,
Expand All @@ -12,8 +12,8 @@ export function renderSync(
renderId?: string;
}
) {
return () => apiRoutes({
forward: inlineServerFunctions({
return () => inlineServerFunctions({
forward: apiRoutes({
edivados marked this conversation as resolved.
Show resolved Hide resolved
async forward(event: FetchEvent): Promise<Response> {
if (
!import.meta.env.DEV &&
Expand Down Expand Up @@ -53,8 +53,8 @@ export function renderAsync(
renderId?: string;
}
) {
return () => apiRoutes({
forward: inlineServerFunctions({
return () => inlineServerFunctions({
forward: apiRoutes({
async forward(event: FetchEvent): Promise<Response> {
if (
!import.meta.env.DEV &&
Expand Down Expand Up @@ -96,8 +96,8 @@ export function renderStream(
onCompleteAll?: (info: { write: (v: string) => void }) => void;
} = {}
) {
return () => apiRoutes({
forward: inlineServerFunctions({
return () => inlineServerFunctions({
forward: apiRoutes({
async forward(event: FetchEvent): Promise<Response> {
if (
!import.meta.env.DEV &&
Expand Down
24 changes: 24 additions & 0 deletions test/api-routes-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ test.describe("api routes", () => {
"src/routes/api/[param]/index.js": js`
import { json } from "solid-start/server";
export let GET = ({ params }) => json(params);
`,
"src/routes/method-not-allowed.jsx": js`
export default function Page() { return <div>page</div>; }
`,
"src/routes/api/method-not-allowed.js": js`
export function POST () { return new Response(); }
`
}
});
Expand Down Expand Up @@ -280,5 +286,23 @@ test.describe("api routes", () => {
expect(res.headers.get("content-type")).toEqual("application/json; charset=utf-8");
expect(await res.json()).toEqual({ static: true });
});

test("should return 405 for undefined handlers on route with only a default export", async () => {
let res = await fixture.requestDocument("/method-not-allowed", { method: "GET" });
expect(res.status).toEqual(200);
["POST", "PUT", "PATCH", "DELETE"].forEach(async method => {
res = await fixture.requestDocument("/method-not-allowed", { method });
expect(res.status).toEqual(405);
})
});

test("should return 405 for undefined handlers on route with only a POST export", async () => {
let res = await fixture.requestDocument("/api/method-not-allowed", { method: "POST" });
expect(res.status).toEqual(200);
["GET", "PUT", "PATCH", "DELETE"].forEach(async method => {
res = await fixture.requestDocument("/api/method-not-allowed", { method });
expect(res.status).toEqual(405);
});
});
}
});
Loading