Google OAuth redirect is going to backend homepage instead of frontend after login.

I have a NestJS backend and TanStack Router in the frontend. Email and password login is working fine, but Google Sign-In redirects to the backend homepage after login. How can I fix this
3 Replies
nomandhoni
nomandhoni2mo ago
server code,
const allowedOrigins = env.CLIENT_URL || "http://localhost:3000";
const SERVER_URL = env.SERVER_URL || "http://localhost:8787";

return {
/**
* The name of the application.
*/
appName: 'zyntime',
/**
* Base path for Better Auth.
* @default "/api/auth"
*/

basePath: '/api',
baseURL: env.BETTER_AUTH_URL,
socialProviders: {
google: {
clientId: env.GOOGLE_CLIENT_ID!,
clientSecret: env.GOOGLE_CLIENT_SECRET!,
redirectURI: `${SERVER_URL}/api/auth/callback/google`,
},
github: {
clientId: env.GITHUB_CLIENT_ID!,
clientSecret: env.GITHUB_CLIENT_SECRET!,
scope: ["read:user", "user:email"],
redirectURI: `${SERVER_URL}/api/auth/callback/github`,
},
},
const allowedOrigins = env.CLIENT_URL || "http://localhost:3000";
const SERVER_URL = env.SERVER_URL || "http://localhost:8787";

return {
/**
* The name of the application.
*/
appName: 'zyntime',
/**
* Base path for Better Auth.
* @default "/api/auth"
*/

basePath: '/api',
baseURL: env.BETTER_AUTH_URL,
socialProviders: {
google: {
clientId: env.GOOGLE_CLIENT_ID!,
clientSecret: env.GOOGLE_CLIENT_SECRET!,
redirectURI: `${SERVER_URL}/api/auth/callback/google`,
},
github: {
clientId: env.GITHUB_CLIENT_ID!,
clientSecret: env.GITHUB_CLIENT_SECRET!,
scope: ["read:user", "user:email"],
redirectURI: `${SERVER_URL}/api/auth/callback/github`,
},
},
and client side code
async function handleSocialSignIn(provider: "google" | "github") {
setLoginError(null);
setLoading(true);
const next = "/dashboard";
try {
await authClient.signIn.social({
provider,
callbackURL: `${window.location.origin}${next}`,
});
} catch (err: any) {
console.error(`${provider} sign-in error:`, err);
setLoginError(err?.message || `Failed to sign in with ${provider}`);
setLoading(false);
}
}
async function handleSocialSignIn(provider: "google" | "github") {
setLoginError(null);
setLoading(true);
const next = "/dashboard";
try {
await authClient.signIn.social({
provider,
callbackURL: `${window.location.origin}${next}`,
});
} catch (err: any) {
console.error(`${provider} sign-in error:`, err);
setLoginError(err?.message || `Failed to sign in with ${provider}`);
setLoading(false);
}
}
this fixed my problem
Nabin47
Nabin47OP2mo ago
Thank you @nomandhoni
!masadam
!masadam2w ago
Beautiful. I was searching it here and there for hours. 😅 So, basically we have to explicitly define the redirectURI in the server to handle the callback from the Google OAuth flow and then also explicitly define the callbackURL in the frontend so the server knows where to redirect after handling the successful login from Google Sign-in (or other OAuth). Many thanks for your help 🙏

Did you find this page helpful?