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 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
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)]);
17 changes: 10 additions & 7 deletions packages/start/fs-router/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ export function stringifyPageRoutes(

export function stringifyAPIRoutes(
/** @type {(RouteConfig)[]} */ flatRoutes,
/** @type {{ lazy?: boolean }} */ options = {}
/** @type {{ lazy?: boolean, islandsRouter?: boolean }} */ options = {}
) {
const jsFile = jsCode();

Expand All @@ -393,12 +393,15 @@ 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]))}`
),
i.componentPath ? `GET: "skip"` : undefined,
...API_METHODS.map(v => {
if (v === "GET" && i.componentPath)
return `${v}: "skip"`;
if (v === "POST" && options.islandsRouter && i.componentPath)
return `${v}: "skip"`;
else if (i.apiPath?.[v])
return `${v}: ${jsFile.addNamedImport(v, path.posix.resolve(i.apiPath[v]))}`;
return `${v}: methodNotAllowed`;
}),
`path: ${JSON.stringify(i.path)}`
]
.filter(Boolean)
Expand Down
5 changes: 4 additions & 1 deletion packages/start/vite/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,10 @@ function solidStartFileSystemRouter(options) {
return {
code: code.replace(
"var api = $API_ROUTES;",
stringifyAPIRoutes(config.solidOptions.router.getFlattenedApiRoutes(true), { lazy })
stringifyAPIRoutes(
config.solidOptions.router.getFlattenedApiRoutes(true),
{ lazy, islandsRouter: !!config.solidOptions.experimental?.islandsRouter }
)
)
};
}
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