Skip to content

Commit e5da06a

Browse files
committed
sync
1 parent 638acd8 commit e5da06a

File tree

2 files changed

+32
-16
lines changed

2 files changed

+32
-16
lines changed

src/router.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,23 @@ describe("router", () => {
230230
};
231231
const req = getRequest({ base, request: fakeReq });
232232
expect(new URL(req.url).href).toBe("http://localhost:3000/auth/callback");
233+
it("should preserve basePath when missing in proxied request", async () => {
234+
const endpoint = createEndpoint(
235+
"/api/auth/get-session",
236+
{
237+
method: "GET",
238+
},
239+
async (c) => {
240+
return c.path;
241+
},
242+
);
243+
const router = createRouter({ endpoint }, { basePath: "/other-app" });
244+
const response = await router.handler(
245+
new Request("http://localhost/api/auth/get-session"),
246+
);
247+
expect(response.status).toBe(200);
248+
const text = await response.text();
249+
expect(text).toBe("/other-app/api/auth/get-session");
233250
});
234251
});
235252

src/router.ts

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -122,21 +122,20 @@ export const createRouter = <E extends Record<string, Endpoint>, Config extends
122122

123123
const processRequest = async (request: Request) => {
124124
const url = new URL(request.url);
125-
const path = config?.basePath
126-
? url.pathname
127-
.split(config.basePath)
128-
.reduce((acc, curr, index) => {
129-
if (index !== 0) {
130-
if (index > 1) {
131-
acc.push(`${config.basePath}${curr}`);
132-
} else {
133-
acc.push(curr);
134-
}
135-
}
136-
return acc;
137-
}, [] as string[])
138-
.join("")
139-
: url.pathname;
125+
const rawPath = url.pathname;
126+
let matchPath = rawPath;
127+
let ctxPath = rawPath;
128+
if (config?.basePath) {
129+
const basePath = config.basePath;
130+
if (rawPath.startsWith(basePath)) {
131+
matchPath = rawPath.slice(basePath.length) || "/";
132+
ctxPath = matchPath;
133+
} else {
134+
matchPath = rawPath;
135+
ctxPath = `${basePath}${rawPath}`;
136+
}
137+
}
138+
const path = matchPath;
140139

141140
if (!path?.length) {
142141
return new Response(null, { status: 404, statusText: "Not Found" });
@@ -162,7 +161,7 @@ export const createRouter = <E extends Record<string, Endpoint>, Config extends
162161

163162
const handler = route.data as Endpoint;
164163
const context = {
165-
path,
164+
path: ctxPath,
166165
method: request.method as "GET",
167166
headers: request.headers,
168167
params: route.params ? (JSON.parse(JSON.stringify(route.params)) as any) : {},

0 commit comments

Comments
 (0)