Skip to content
Open
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
16 changes: 16 additions & 0 deletions src/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
31 changes: 15 additions & 16 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,21 +122,20 @@ export const createRouter = <E extends Record<string, Endpoint>, 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" });
Expand All @@ -162,7 +161,7 @@ export const createRouter = <E extends Record<string, Endpoint>, 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) : {},
Expand Down