[GH-ISSUE #5696] Better Auth callback redirects to server (Hono 8787) port instead of client port 3000. #18958

Closed
opened 2026-04-15 17:42:06 -05:00 by GiteaMirror · 4 comments
Owner

Originally created by @jeanmako on GitHub (Oct 31, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/5696

Originally assigned to: @Paola3stefania on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";

export const auth = betterAuth({
baseURL: "http://localhost:8787", // If not set, does not go anywhere. If set to 3000, redirect_mismatch since the server runs on 8787
database: drizzleAdapter(db, {
provider: "pg",
}),
socialProviders: {
google: {
clientId: String(process.env.GOOGLE_CLIENT_ID),
clientSecret: String(process.env.GOOGLE_CLIENT_SECRET),
},
github: {
clientId: String(process.env.GITHUB_CLIENT_ID),
clientSecret: String(process.env.GITHUB_CLIENT_SECRET),
}, // TODO: Probably remove github
spotify: {
clientId: String(process.env.SPOTIFY_CLIENT_ID),
clientSecret: String(process.env.SPOTIFY_CLIENT_SECRET),
},
apple: {
clientId: String(process.env.APPLE_CLIENT_ID),
clientSecret: String(process.env.APPLE_CLIENT_SECRET),
},
},
})

import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:8787"
})

import { app } from "@monorepo/api";
import { auth } from "@monorepo/auth/lib/auth";
import { cors } from "hono/cors";

app.use(
"/api/auth/*",
cors({
origin: "http://localhost:3000",
allowHeaders: ["Content-Type", "Authorization"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length"],
maxAge: 600,
credentials: true,
})
);

app.use("*", async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers });
if (!session) {
c.set("user", null);
c.set("session", null);
return next();
}
c.set("user", session.user);
c.set("session", session.session);
return next();
});

app.on(["POST", "GET"], "/api/auth/*", (c) => {
return auth.handler(c.req.raw);
});

app.get("/api/me", (c) => {
const user = c.get("user");
const session = c.get("session");
if (!user) {
return c.json({ error: "Not authenticated" }, 401);
}
return c.json({ user, session });
});

Bun.serve({
fetch: app.fetch,
port: 8787,
idleTimeout: 20,
});

Current vs. Expected behavior

After the social provider redirects to the redirect URI (http://localhost:8787/api/auth/callback/google) for Google, the Better Auth callback should send me back to the client, but instead, I am getting sent back to http://localhost:8787. I was thinking maybe I did something wrong, but I have tried many times, changed ports, and nothing. It was working fine on the preview version of the app, maybe version 1.3.34 brought this up.

What version of Better Auth are you using?

1.3.34

System info

{
  "system": {
    "platform": "win32",
    "arch": "x64",
    "version": "Windows 11 Pro",
    "release": "10.0.26200",
    "cpuCount": 4,
    "cpuModel": "11th Gen Intel(R) Core(TM) i3-1115G4 @ 3.00GHz",
    "totalMemory": "11.79 GB",
    "freeMemory": "1.67 GB"
  },
  "node": {
    "version": "v22.17.0",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "10.9.2"
  },
  "frameworks": null,
  "databases": null,
  "betterAuth": {
    "version": "Unknown",
    "config": null
  }
}

Which area(s) are affected? (Select all that apply)

Backend, Client

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
  emailAndPassword: {  
    enabled: true
  },
});

Additional context

No response

Originally created by @jeanmako on GitHub (Oct 31, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/5696 Originally assigned to: @Paola3stefania on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; export const auth = betterAuth({ baseURL: "http://localhost:8787", // If not set, does not go anywhere. If set to 3000, redirect_mismatch since the server runs on 8787 database: drizzleAdapter(db, { provider: "pg", }), socialProviders: { google: { clientId: String(process.env.GOOGLE_CLIENT_ID), clientSecret: String(process.env.GOOGLE_CLIENT_SECRET), }, github: { clientId: String(process.env.GITHUB_CLIENT_ID), clientSecret: String(process.env.GITHUB_CLIENT_SECRET), }, // TODO: Probably remove github spotify: { clientId: String(process.env.SPOTIFY_CLIENT_ID), clientSecret: String(process.env.SPOTIFY_CLIENT_SECRET), }, apple: { clientId: String(process.env.APPLE_CLIENT_ID), clientSecret: String(process.env.APPLE_CLIENT_SECRET), }, }, }) 2. import { createAuthClient } from "better-auth/react" export const authClient = createAuthClient({ /** The base URL of the server (optional if you're using the same domain) */ baseURL: "http://localhost:8787" }) 3. import { app } from "@monorepo/api"; import { auth } from "@monorepo/auth/lib/auth"; import { cors } from "hono/cors"; app.use( "/api/auth/*", cors({ origin: "http://localhost:3000", allowHeaders: ["Content-Type", "Authorization"], allowMethods: ["POST", "GET", "OPTIONS"], exposeHeaders: ["Content-Length"], maxAge: 600, credentials: true, }) ); app.use("*", async (c, next) => { const session = await auth.api.getSession({ headers: c.req.raw.headers }); if (!session) { c.set("user", null); c.set("session", null); return next(); } c.set("user", session.user); c.set("session", session.session); return next(); }); app.on(["POST", "GET"], "/api/auth/*", (c) => { return auth.handler(c.req.raw); }); app.get("/api/me", (c) => { const user = c.get("user"); const session = c.get("session"); if (!user) { return c.json({ error: "Not authenticated" }, 401); } return c.json({ user, session }); }); Bun.serve({ fetch: app.fetch, port: 8787, idleTimeout: 20, }); ### Current vs. Expected behavior After the social provider redirects to the redirect URI (http://localhost:8787/api/auth/callback/google) for Google, the Better Auth callback should send me back to the client, but instead, I am getting sent back to http://localhost:8787. I was thinking maybe I did something wrong, but I have tried many times, changed ports, and nothing. It was working fine on the preview version of the app, maybe version 1.3.34 brought this up. ### What version of Better Auth are you using? 1.3.34 ### System info ```bash { "system": { "platform": "win32", "arch": "x64", "version": "Windows 11 Pro", "release": "10.0.26200", "cpuCount": 4, "cpuModel": "11th Gen Intel(R) Core(TM) i3-1115G4 @ 3.00GHz", "totalMemory": "11.79 GB", "freeMemory": "1.67 GB" }, "node": { "version": "v22.17.0", "env": "development" }, "packageManager": { "name": "npm", "version": "10.9.2" }, "frameworks": null, "databases": null, "betterAuth": { "version": "Unknown", "config": null } } ``` ### Which area(s) are affected? (Select all that apply) Backend, Client ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, }); ``` ### Additional context _No response_
GiteaMirror added the lockedcoreoauthbug labels 2026-04-15 17:42:06 -05:00
Author
Owner

@better-auth-agent[bot] commented on GitHub (Oct 31, 2025):

It appears that the callback flow is now using the server’s base URL (port 8787) instead of your client’s expected URL (port 3000). This is similar to a known issue where the “Return to Application” link or post‐login redirection was showing the backend URL rather than the frontend URL.

To troubleshoot and resolve the issue try the following steps:

  1. Ensure that your configuration distinguishes between the backend endpoint (used for authentication requests) and the frontend URL (where users should end up after logging in). In your auth configuration for Better Auth, verify if there is an option (for example “frontendBaseURL” or a similar parameter) that explicitly tells the callback where to redirect after a successful login. If such an option is available, set it to "http://localhost:3000".

  2. Alternatively, if your social provider settings allow you to specify a redirectURI or callbackURL, update it so that after the OAuth flow the redirection is performed with the client’s URL rather than the server’s (i.e. use "http://localhost:3000" or pass it as a query parameter that Better Auth can pick up).

  3. Double‑check your client’s instantiation (using createAuthClient) so that it properly communicates the client’s base URL. If both the server and client are using the same baseURL configuration value, the system may default to the backend port.

  4. Since you mentioned that this behavior appeared starting in version 1.3.34, consider checking the release notes for any changes regarding redirection or returning to the application post‑authentication. There may be a regression or configuration tweak introduced in that version that needs to be addressed.

Taking these actions should help Better Auth correctly redirect users back to port 3000 instead of remaining on 8787. If after adjusting these settings the issue persists, it might be worthwhile to reach out to the maintainers, since this behavior seems to be an unintended regression.

(References: similar issues with wrong “Return to Application” URLs have been noted in previous reports [1].)

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3472026846 --> @better-auth-agent[bot] commented on GitHub (Oct 31, 2025): It appears that the callback flow is now using the server’s base URL (port 8787) instead of your client’s expected URL (port 3000). This is similar to a known issue where the “Return to Application” link or post‐login redirection was showing the backend URL rather than the frontend URL. To troubleshoot and resolve the issue try the following steps: 1. Ensure that your configuration distinguishes between the backend endpoint (used for authentication requests) and the frontend URL (where users should end up after logging in). In your auth configuration for Better Auth, verify if there is an option (for example “frontendBaseURL” or a similar parameter) that explicitly tells the callback where to redirect after a successful login. If such an option is available, set it to "http://localhost:3000". 2. Alternatively, if your social provider settings allow you to specify a redirectURI or callbackURL, update it so that after the OAuth flow the redirection is performed with the client’s URL rather than the server’s (i.e. use "http://localhost:3000" or pass it as a query parameter that Better Auth can pick up). 3. Double‑check your client’s instantiation (using createAuthClient) so that it properly communicates the client’s base URL. If both the server and client are using the same baseURL configuration value, the system may default to the backend port. 4. Since you mentioned that this behavior appeared starting in version 1.3.34, consider checking the release notes for any changes regarding redirection or returning to the application post‑authentication. There may be a regression or configuration tweak introduced in that version that needs to be addressed. Taking these actions should help Better Auth correctly redirect users back to port 3000 instead of remaining on 8787. If after adjusting these settings the issue persists, it might be worthwhile to reach out to the maintainers, since this behavior seems to be an unintended regression. (References: similar issues with wrong “Return to Application” URLs have been noted in previous reports [[1]](https://github.com/better-auth/better-auth/issues/5541).) <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@Rjshakya commented on GitHub (Nov 5, 2025):

Hey try adding, callback url , in your signin .
Like this ;

await authClient.signIn.social({

  provider: "google",
  callbackURL: `${clientUrl}/dashboard`,
  requestSignUp: true,

  });
<!-- gh-comment-id:3490741713 --> @Rjshakya commented on GitHub (Nov 5, 2025): Hey try adding, callback url , in your signin . Like this ; await authClient.signIn.social({ provider: "google", callbackURL: `${clientUrl}/dashboard`, requestSignUp: true, });
Author
Owner

@Paola3stefania commented on GitHub (Jan 9, 2026):

hi @jeanmako as @Rjshakya mentioned - ty btw :) - you need to add the callback url

adding a callbackURL to the sign-in call solves it.

When you call signIn.social() without specifying a callbackURL, Better Auth doesn't know where to send the user after OAuth completes. It defaults to the baseURL (your server at http://localhost:8787), not your client at http://localhost:3000.

Pass the callbackURL parameter when calling signIn.social() on the client:

// On your client (React app at localhost:3000)
await authClient.signIn.social({
  provider: "google",
  callbackURL: "http://localhost:3000/dashboard", // or wherever you want to redirect after login
});

You'll also need to add your client origin to trustedOrigins in your auth config:

export const auth = betterAuth({
  baseURL: "http://localhost:8787",
  trustedOrigins: ["http://localhost:3000"], // Add your client origin
  // ... rest of config
});
```ts

let me know if its working for you.
cheers !
<!-- gh-comment-id:3730577136 --> @Paola3stefania commented on GitHub (Jan 9, 2026): hi @jeanmako as @Rjshakya mentioned - ty btw :) - you need to add the callback url **adding a `callbackURL` to the sign-in call solves it**. When you call `signIn.social()` without specifying a `callbackURL`, Better Auth doesn't know where to send the user after OAuth completes. It defaults to the `baseURL` (your server at `http://localhost:8787`), not your client at `http://localhost:3000`. Pass the `callbackURL` parameter when calling `signIn.social()` on the client: ```ts // On your client (React app at localhost:3000) await authClient.signIn.social({ provider: "google", callbackURL: "http://localhost:3000/dashboard", // or wherever you want to redirect after login }); ``` You'll also need to add your client origin to **trustedOrigins** in your auth config: ```ts export const auth = betterAuth({ baseURL: "http://localhost:8787", trustedOrigins: ["http://localhost:3000"], // Add your client origin // ... rest of config }); ```ts let me know if its working for you. cheers !
Author
Owner

@github-actions[bot] commented on GitHub (Apr 4, 2026):

This issue has been locked as it was closed more than 7 days ago. If you're experiencing a similar problem or you have additional context, please open a new issue and reference this one.

<!-- gh-comment-id:4185771582 --> @github-actions[bot] commented on GitHub (Apr 4, 2026): This issue has been locked as it was closed more than 7 days ago. If you're experiencing a similar problem or you have additional context, please open a new issue and reference this one.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#18958