Adding Google Sign-In to your Supabase-powered Next.js app involves configuring Supabase, setting up the Google Cloud project for OAuth credentials, and integrating the sign-in flow in your Next.js code. Here's a clear breakdown of the steps.
https://<your-supabase-url>.supabase.co/auth/v1/callback).<your-supabase-url>.supabase.co) to Authorized Domains.https://your-nextjs-app.comhttp://localhost:3000npm install @supabase/supabase-js
Create a component to handle Google Sign-In, and use Google's Sign-In script to generate the login button.
// components/GoogleSignIn.tsx
"use client";
const GoogleSignIn = () => {
const supabase = createClient();
useEffect(() => {
if (window.google) {
window.google.accounts.id.initialize({
client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
callback: handleGoogleSignIn,
});
window.google.accounts.id.renderButton(
document.getElementById("googleSignInDiv"),
{ theme: "outline", size: "large" }
);
}
}, []);
const handleGoogleSignIn = async (response: any) => {
const { data, error } = await supabase.auth.signInWithIdToken({
provider: "google",
token: response.credential,
});
if (error) {
console.error("Google sign-in failed", error);
} else {
console.log("Signed in with Google", data);
// Handle redirection or further logic
}
};
return (
<>
<Script src="https://accounts.google.com/gsi/client" async defer />
<div id="googleSignInDiv"></div>
</>
);
};
export default GoogleSignIn;
// pages/login.tsx
export default function LoginPage() {
return (
<div>
<h1>Login to Your App</h1>
<GoogleSignIn />
</div>
);
}
Ensure you have the correct environment variables in your Next.js app:
NEXT_PUBLIC_GOOGLE_CLIENT_ID=<your-google-client-id>
Add the NEXT_PUBLIC_GOOGLE_CLIENT_ID in your .env.local file for both local and production environments.
With these steps, you can easily integrate Google authentication in your Next.js app with Supabase.