fix: custom base path not working

This commit is contained in:
Bereket Engida
2024-10-09 13:53:36 +03:00
parent 6862e1f433
commit b77a698241
4 changed files with 36 additions and 9 deletions

View File

@@ -162,6 +162,7 @@ export const router = <C extends AuthContext, Option extends BetterAuthOptions>(
) => {
const { api, middlewares } = getEndpoints(ctx, options);
const basePath = new URL(ctx.baseURL).pathname;
console.log({ basePath });
return createRouter(api, {
extraContext: ctx,

View File

@@ -3,6 +3,7 @@ import { getEndpoints, router } from "./api";
import { init } from "./init";
import type { BetterAuthOptions } from "./types/options";
import type { InferPluginTypes, InferSession, InferUser } from "./types";
import { getBaseURL } from "./utils/base-url";
type InferAPI<API> = Omit<
API,
@@ -19,21 +20,15 @@ export const betterAuth = <O extends BetterAuthOptions>(options: O) => {
const authContext = init(options);
const { api } = getEndpoints(authContext, options);
type API = typeof api;
type X = API extends { [key in infer K]: Endpoint }
? K extends string
? API[K]["options"]["metadata"] extends { isAction: false }
? K
: never
: never
: never;
return {
handler: async (request: Request) => {
const ctx = await authContext;
const basePath = ctx.options.basePath;
const basePath = ctx.options.basePath || "/api/auth";
const url = new URL(request.url);
if (!ctx.options.baseURL) {
const baseURL = `${url.origin}/api/auth`;
const baseURL =
getBaseURL(undefined, basePath) || `${url.origin}${basePath}`;
ctx.options.baseURL = baseURL;
ctx.baseURL = baseURL;
}

View File

@@ -8,6 +8,7 @@ export const getClientConfig = <O extends ClientOptions>(options?: O) => {
const $fetch = createFetch({
baseURL: getBaseURL(options?.fetchOptions?.baseURL || options?.baseURL),
credentials: "include",
method: "GET",
...options?.fetchOptions,
plugins: [
csrfPlugin,

View File

@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { init } from "./init";
import Database from "better-sqlite3";
import { betterAuth } from "./auth";
import { createAuthClient } from "./client";
describe("init", async () => {
const database = new Database(":memory:");
@@ -44,4 +46,32 @@ describe("init", async () => {
});
expect(res).toMatchObject(changedCtx);
});
it("should work with custom path", async () => {
const customPath = "/custom-path";
const ctx = await init({
database,
basePath: customPath,
baseURL: "http://localhost:3000",
});
expect(ctx.baseURL).toBe(`http://localhost:3000${customPath}`);
const res = betterAuth({
database,
basePath: customPath,
});
const client = createAuthClient({
baseURL: `http://localhost:3000/custom-path`,
fetchOptions: {
customFetchImpl: async (url, init) => {
return res.handler(new Request(url, init));
},
},
});
const ok = await client.$fetch("/ok");
expect(ok.data).toMatchObject({
ok: true,
});
});
});