mirror of
https://github.com/LukeHagar/better-auth.git
synced 2025-12-07 04:19:22 +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();
|
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 {
|
function checkHasPath(url: string): boolean {
|
||||||
try {
|
try {
|
||||||
const parsedUrl = new URL(url);
|
const parsedUrl = new URL(url);
|
||||||
return parsedUrl.pathname !== "/";
|
const pathname = parsedUrl.pathname.replace(/\/+$/, "") || "/";
|
||||||
|
return pathname !== "/";
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new BetterAuthError(
|
throw new BetterAuthError(
|
||||||
`Invalid base URL: ${url}. Please provide a valid base URL.`,
|
`Invalid base URL: ${url}. Please provide a valid base URL.`,
|
||||||
@@ -17,8 +18,15 @@ function withPath(url: string, path = "/api/auth") {
|
|||||||
if (hasPath) {
|
if (hasPath) {
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const trimmedUrl = url.replace(/\/+$/, "");
|
||||||
|
|
||||||
|
if (!path || path === "/") {
|
||||||
|
return trimmedUrl;
|
||||||
|
}
|
||||||
|
|
||||||
path = path.startsWith("/") ? path : `/${path}`;
|
path = path.startsWith("/") ? path : `/${path}`;
|
||||||
return `${url.replace(/\/+$/, "")}${path}`;
|
return `${trimmedUrl}${path}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getBaseURL(
|
export function getBaseURL(
|
||||||
|
|||||||
Reference in New Issue
Block a user