diff --git a/src/router.test.ts b/src/router.test.ts index 5e9cb13..d278998 100644 --- a/src/router.test.ts +++ b/src/router.test.ts @@ -231,6 +231,22 @@ describe("router", () => { const req = getRequest({ base, request: fakeReq }); expect(new URL(req.url).href).toBe("http://localhost:3000/auth/callback"); }); + it("should preserve basePath when missing in proxied request", async () => { + const endpoint = createEndpoint( + "/api/auth/get-session", + { + method: "GET", + }, + async (c) => { + return c.path; + }, + ); + const router = createRouter({ endpoint }, { basePath: "/other-app" }); + const response = await router.handler(new Request("http://localhost/api/auth/get-session")); + expect(response.status).toBe(200); + const text = await response.text(); + expect(text).toBe("/other-app/api/auth/get-session"); + }); }); describe("route middleware", () => { diff --git a/src/router.ts b/src/router.ts index 7c7f3cb..b1864ba 100644 --- a/src/router.ts +++ b/src/router.ts @@ -122,21 +122,20 @@ export const createRouter = , Config extends const processRequest = async (request: Request) => { const url = new URL(request.url); - const path = config?.basePath - ? url.pathname - .split(config.basePath) - .reduce((acc, curr, index) => { - if (index !== 0) { - if (index > 1) { - acc.push(`${config.basePath}${curr}`); - } else { - acc.push(curr); - } - } - return acc; - }, [] as string[]) - .join("") - : url.pathname; + const rawPath = url.pathname; + let matchPath = rawPath; + let ctxPath = rawPath; + if (config?.basePath) { + const basePath = config.basePath; + if (rawPath.startsWith(basePath)) { + matchPath = rawPath.slice(basePath.length) || "/"; + ctxPath = matchPath; + } else { + matchPath = rawPath; + ctxPath = `${basePath}${rawPath}`; + } + } + const path = matchPath; if (!path?.length) { return new Response(null, { status: 404, statusText: "Not Found" }); @@ -162,7 +161,7 @@ export const createRouter = , Config extends const handler = route.data as Endpoint; const context = { - path, + path: ctxPath, method: request.method as "GET", headers: request.headers, params: route.params ? (JSON.parse(JSON.stringify(route.params)) as any) : {},