I set up Google Authentication with Supabase, but when I try to log in, it redirects to the homepage instead of logging in. Instead of successfully logging in, I am redirected to the homepage, and the URL changes to: https://www.myurl.com/?code=5e22291a-e4d1-4e55-9e0a-48d902b5235b.
Oauthsignin.tsx
'use client';
import Button from '@/components/ui/Button/Button';
import { signInWithOAuth } from '@/utils/auth-helpers/client';
import { type Provider } from '@supabase/supabase-js';
import { FaGoogle } from "react-icons/fa";
import { useState } from 'react';
type OAuthProviders = {
name: Provider;
displayName: string;
icon: JSX.Element;
};
export default function OauthSignIn() {
const oAuthProviders: OAuthProviders[] = [
{
name: 'google',
displayName: 'Google',
icon: <FaGoogle className="h-5 w-5" />
}
/* Add desired OAuth providers here */
];
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
setIsSubmitting(true); // Disable the button while the request is being handled
await signInWithOAuth(e);
setIsSubmitting(false);
};
return (
<div className="mt-8">
{oAuthProviders.map((provider) => (
<form
key={provider.name}
className="pb-2"
onSubmit={(e) => handleSubmit(e)}
>
<input type="hidden" name="provider" value={provider.name} />
<Button
variant="slim"
type="submit"
className="w-full"
loading={isSubmitting}
>
<span className="mr-2">{provider.icon}</span>
<span>{provider.displayName}</span>
</Button>
</form>
))}
</div>
);
}
client.ts
'use client';
import { createClient } from '@/utils/supabase/client';
import { type Provider } from '@supabase/supabase-js';
import { getURL } from '@/utils/helpers';
import { redirectToPath } from './server';
import { AppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime';
export async function handleRequest(
e: React.FormEvent<HTMLFormElement>,
requestFunc: (formData: FormData) => Promise<string>,
router: AppRouterInstance | null = null
): Promise<boolean | void> {
// Prevent default form submission refresh
e.preventDefault();
const formData = new FormData(e.currentTarget);
const redirectUrl: string = await requestFunc(formData);
if (router) {
// If client-side router is provided, use it to redirect
return router.push(redirectUrl);
} else {
// Otherwise, redirect server-side
return await redirectToPath(redirectUrl);
}
}
export async function signInWithOAuth(e: React.FormEvent<HTMLFormElement>) {
// Prevent default form submission refresh
e.preventDefault();
const formData = new FormData(e.currentTarget);
const provider = String(formData.get('provider')).trim() as Provider;
// Create client-side supabase client and call signInWithOAuth
const supabase = createClient();
const redirectURL = getURL('/auth/callback');
await supabase.auth.signInWithOAuth({
provider: provider,
options: {
redirectTo: redirectURL
}
});
}