fix(url): handle empty and root path in withPath, prevent double slashes, add tests (#5091)

This commit is contained in:
surafel
2025-10-06 19:37:00 +03:00
committed by GitHub
parent e6d82a83fe
commit 4e883a007f
2 changed files with 36 additions and 2 deletions

View File

@@ -219,4 +219,30 @@ describe("init", async () => {
});
expect(initFn).toHaveBeenCalled();
});
it("handles empty basePath", async () => {
const res = await init({
database,
baseURL: "http://localhost:5147/",
basePath: "",
});
expect(res.baseURL).toBe("http://localhost:5147");
});
it("handles root basePath", async () => {
const res = await init({
database,
baseURL: "http://localhost:5147/",
basePath: "/",
});
expect(res.baseURL).toBe("http://localhost:5147");
});
it("normalizes trailing slashes with default path", async () => {
const res = await init({
database,
baseURL: "http://localhost:5147////",
});
expect(res.baseURL).toBe("http://localhost:5147/api/auth");
});
});

View File

@@ -4,7 +4,8 @@ import { BetterAuthError } from "../error";
function checkHasPath(url: string): boolean {
try {
const parsedUrl = new URL(url);
return parsedUrl.pathname !== "/";
const pathname = parsedUrl.pathname.replace(/\/+$/, "") || "/";
return pathname !== "/";
} catch (error) {
throw new BetterAuthError(
`Invalid base URL: ${url}. Please provide a valid base URL.`,
@@ -17,8 +18,15 @@ function withPath(url: string, path = "/api/auth") {
if (hasPath) {
return url;
}
const trimmedUrl = url.replace(/\/+$/, "");
if (!path || path === "/") {
return trimmedUrl;
}
path = path.startsWith("/") ? path : `/${path}`;
return `${url.replace(/\/+$/, "")}${path}`;
return `${trimmedUrl}${path}`;
}
export function getBaseURL(