Skip to content

Commit c928b9c

Browse files
lxsmnsycclaude
andcommitted
fix(server): keep the API route matcher out of the client bundle
- Move the radix3 API router and matchAPIRoute into a server-only api-routes.ts. - routes.ts keeps only pageRoutes, which the client needs. - Match routes that only export an OPTIONS handler. - Add a build test that checks the router is not in client output. Fixes #2361 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5de5afd commit c928b9c

6 files changed

Lines changed: 126 additions & 81 deletions

File tree

‎.changeset/client-api-router.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/start": patch
3+
---
4+
5+
Keep the API route matcher out of the client bundle. It is only used on the server, but the client loaded it with the page routes, which added about 2.5 KB of unused code. Routes that only export an `OPTIONS` handler are now matched as API routes.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { describe, expect, it } from "vitest";
2+
import { getBuildOutputDirs, getFiles, readFileContent } from "~/utils/build-output-utils";
3+
4+
// Regression test for https://github.com/solidjs/solid-start/issues/2361.
5+
// The client imports `pageRoutes`, which used to share a module with the API
6+
// router. Building that router at module scope kept it and radix3 in the
7+
// client bundle, even though the client has no API routes to match.
8+
const MARKER = "Optional parameters are not supported in API routes";
9+
10+
describe("API router is excluded from the client bundle", () => {
11+
it("ships the API router to the server only", async () => {
12+
const { serverOutputRoot, clientOutputRoot } = getBuildOutputDirs();
13+
14+
const serverFiles = await getFiles(serverOutputRoot, /\.(m?js)$/);
15+
const serverContents = await Promise.all(serverFiles.map(readFileContent));
16+
expect(
17+
serverContents.some(content => content.includes(MARKER)),
18+
"API router not found in the server output",
19+
).toBe(true);
20+
21+
const clientFiles = await getFiles(clientOutputRoot, /\.(m?js)$/);
22+
expect(clientFiles.length, "No client JS files found").toBeGreaterThan(0);
23+
for (const file of clientFiles) {
24+
const content = await readFileContent(file);
25+
expect(content, `API router leaked into: ${file}`).not.toContain(MARKER);
26+
}
27+
});
28+
});

packages/start/src/server/routes.spec.ts renamed to packages/start/src/server/api-routes.spec.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ vi.mock("solid-start:routes", () => ({
1414
},
1515
{ path: "/spa/*404", page: true, $GET: GET },
1616
{ path: "/api/*rest", $GET: GET },
17+
{ path: "/cors", $OPTIONS: GET },
1718
],
1819
}));
1920

20-
const { matchAPIRoute } = await import("./routes.ts");
21+
const { matchAPIRoute } = await import("./api-routes.ts");
2122

2223
describe("matchAPIRoute", () => {
2324
it("marks a route with a page and an API handler as a page", () => {
@@ -31,4 +32,8 @@ describe("matchAPIRoute", () => {
3132
it("does not mark an API-only route as a page", () => {
3233
expect(matchAPIRoute("/api/missing", "GET")?.isPage).toBe(false);
3334
});
35+
36+
it("matches a route that only exports OPTIONS", () => {
37+
expect(matchAPIRoute("/cors", "OPTIONS")?.handler).toBe(GET);
38+
});
3439
});
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// @ts-expect-error
2+
import fileRoutes from "solid-start:routes";
3+
import { createRouter } from "radix3";
4+
5+
import type { Route } from "./routes.ts";
6+
import type { FetchEvent } from "./types.ts";
7+
8+
// The API router lives apart from `pageRoutes` so the client bundle, which
9+
// imports `pageRoutes`, doesn't include radix3 or build this router.
10+
const router = createRouter({
11+
routes: (fileRoutes as unknown as Route[]).reduce(
12+
(memo, route) => {
13+
if (!containsHTTP(route)) return memo;
14+
const path = route.path
15+
.replace(/\([^)/]+\)/g, "")
16+
.replace(/\/+/g, "/")
17+
.replace(/\*([^/]*)/g, (_, m) => `**:${m}`)
18+
.split("/")
19+
.map(s => (s.startsWith(":") || s.startsWith("*") ? s : encodeURIComponent(s)))
20+
.join("/");
21+
if (/:[^/]*\?/g.test(path)) {
22+
throw new Error(`Optional parameters are not supported in API routes: ${path}`);
23+
}
24+
if (memo[path]) {
25+
throw new Error(
26+
`Duplicate API routes for "${path}" found at "${memo[path]!.route.path}" and "${
27+
route.path
28+
}"`,
29+
);
30+
}
31+
memo[path] = { route };
32+
return memo;
33+
},
34+
{} as Record<string, { route: Route }>,
35+
),
36+
});
37+
38+
function containsHTTP(route: Route) {
39+
return (
40+
route["$HEAD"] ||
41+
route["$GET"] ||
42+
route["$POST"] ||
43+
route["$PUT"] ||
44+
route["$PATCH"] ||
45+
route["$DELETE"] ||
46+
route["$OPTIONS"]
47+
);
48+
}
49+
50+
export function matchAPIRoute(
51+
path: string,
52+
method: string,
53+
):
54+
| {
55+
params?: Record<string, any>;
56+
handler: {
57+
import: () => Promise<Record<string, (e: FetchEvent) => Promise<any>>>;
58+
};
59+
isPage: boolean;
60+
}
61+
| undefined {
62+
const match = router.lookup(path);
63+
if (match && match.route) {
64+
const route = match.route;
65+
66+
// Find the appropriate handler for the HTTP method
67+
const handler = method === "HEAD" ? route.$HEAD || route.$GET : route[`$${method}`];
68+
69+
if (handler === undefined) return;
70+
71+
// Check if this is a page route. SPA builds leave page components out of
72+
// the server routes, so this can't depend on `$component`.
73+
const isPage = route.page === true;
74+
75+
// Return comprehensive route information
76+
return {
77+
handler,
78+
params: match.params,
79+
isPage,
80+
};
81+
}
82+
83+
return undefined;
84+
}

‎packages/start/src/server/handler.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { createRoutes } from "../router.tsx";
88
import { decorateHandler, decorateMiddleware } from "./fetchEvent.ts";
99
import { sendEarlyHints } from "./early-hints.ts";
1010
import { getSsrManifest } from "./manifest/ssr-manifest.ts";
11-
import { matchAPIRoute } from "./routes.ts";
11+
import { matchAPIRoute } from "./api-routes.ts";
1212
import { handleServerFunction } from "../fns/handler.ts";
1313
import type { APIEvent, FetchEvent, HandlerOptions, PageEvent, StartHandler } from "./types.ts";
1414
import { getExpectedRedirectStatus } from "./util.ts";
Lines changed: 2 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
// @ts-expect-error
22
import fileRoutes from "solid-start:routes";
3-
import { createRouter } from "radix3";
43

5-
import type { FetchEvent } from "./types.ts";
6-
7-
interface Route {
4+
export interface Route {
85
path: string;
96
id: string;
107
children?: Route[];
@@ -16,6 +13,7 @@ interface Route {
1613
$PUT?: any;
1714
$PATCH?: any;
1815
$DELETE?: any;
16+
$OPTIONS?: any;
1917
}
2018

2119
export const pageRoutes = defineRoutes((fileRoutes as unknown as Route[]).filter(o => o.page));
@@ -50,78 +48,3 @@ function defineRoutes(fileRoutes: Route[]) {
5048
return processRoute(prevRoutes, route, route.path, route.path);
5149
}, []);
5250
}
53-
54-
const router = createRouter({
55-
routes: (fileRoutes as unknown as Route[]).reduce(
56-
(memo, route) => {
57-
if (!containsHTTP(route)) return memo;
58-
const path = route.path
59-
.replace(/\([^)/]+\)/g, "")
60-
.replace(/\/+/g, "/")
61-
.replace(/\*([^/]*)/g, (_, m) => `**:${m}`)
62-
.split("/")
63-
.map(s => (s.startsWith(":") || s.startsWith("*") ? s : encodeURIComponent(s)))
64-
.join("/");
65-
if (/:[^/]*\?/g.test(path)) {
66-
throw new Error(`Optional parameters are not supported in API routes: ${path}`);
67-
}
68-
if (memo[path]) {
69-
throw new Error(
70-
`Duplicate API routes for "${path}" found at "${memo[path]!.route.path}" and "${
71-
route.path
72-
}"`,
73-
);
74-
}
75-
memo[path] = { route };
76-
return memo;
77-
},
78-
{} as Record<string, { route: Route }>,
79-
),
80-
});
81-
82-
function containsHTTP(route: Route) {
83-
return (
84-
route["$HEAD"] ||
85-
route["$GET"] ||
86-
route["$POST"] ||
87-
route["$PUT"] ||
88-
route["$PATCH"] ||
89-
route["$DELETE"]
90-
);
91-
}
92-
93-
export function matchAPIRoute(
94-
path: string,
95-
method: string,
96-
):
97-
| {
98-
params?: Record<string, any>;
99-
handler: {
100-
import: () => Promise<Record<string, (e: FetchEvent) => Promise<any>>>;
101-
};
102-
isPage: boolean;
103-
}
104-
| undefined {
105-
const match = router.lookup(path);
106-
if (match && match.route) {
107-
const route = match.route;
108-
109-
// Find the appropriate handler for the HTTP method
110-
const handler = method === "HEAD" ? route.$HEAD || route.$GET : route[`$${method}`];
111-
112-
if (handler === undefined) return;
113-
114-
// Check if this is a page route. SPA builds leave page components out of
115-
// the server routes, so this can't depend on `$component`.
116-
const isPage = route.page === true;
117-
118-
// Return comprehensive route information
119-
return {
120-
handler,
121-
params: match.params,
122-
isPage,
123-
};
124-
}
125-
126-
return undefined;
127-
}

0 commit comments

Comments
 (0)