Correct way to determine the baseURL?

Hey there 👋 What is the recommended way in Next.js to determine the baseURL on the client? The docs tell us to create an environment variable BETTER_AUTH_URL. However, I don't see where the docs recommends that we use this env variable. On the client, the example used only shows an explicitly defined string. In Next.js, I have used the following:
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
baseURL: NEXT_PUBLIC_BETTER_AUTH_BASE_URL
// or... NEXT_PUBLIC_APP_DOMAIN
})
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
baseURL: NEXT_PUBLIC_BETTER_AUTH_BASE_URL
// or... NEXT_PUBLIC_APP_DOMAIN
})
However, I am inclined to follow a method usually used in tRPC. On the client, we typically do something like this to determine the URL:
function getBaseUrl() {
if (typeof window !== "undefined") return window.location.origin;
if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;
return `http://localhost:${process.env.PORT ?? 3000}`;
}
function getBaseUrl() {
if (typeof window !== "undefined") return window.location.origin;
if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;
return `http://localhost:${process.env.PORT ?? 3000}`;
}
So, should we really just be using a function like getBaseUrl() on the client to determine the auth location? Also, is BETTER_AUTH_URL used somewhere internally that I'm not seeing?
5 Replies
Json 👺
Json 👺OP3mo ago
It would be nice if we could explicitly determine the baseURL on the server as well, this way we could just use a single function like the one used in tRPC 🙂 Thanks
bekacru
bekacru3mo ago
if you're using nextjs, you don't need to provide the baseURL. When the request is from the client, it'll infer the url from the current origin and on the server it can use BETTER_AUTH_URL.
Json 👺
Json 👺OP3mo ago
Perfect! Have you considered allowing explicit baseURL definition (on the server) to cut down on environment variables? An extra variable is no big deal, but I'm curious.
bekacru
bekacru3mo ago
Oh, you can pass baseURL to the auth config as well. And I also really want to make BETTER_AUTH_URL not a thing or at least truly optional, hopefully, we'll do that soon.
Json 👺
Json 👺OP3mo ago
👏

Did you find this page helpful?