mirror of
https://github.com/LukeHagar/better-auth.git
synced 2025-12-06 12:27:44 +00:00
fix(url): handle empty and root path in withPath, prevent double slashes, add tests (#5091)
This commit is contained in:
@@ -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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user