October 15, 2024
O. Wolfson
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.com
http://localhost:3000
bashnpm install @supabase/supabase-js
Create a component to handle Google Sign-In, and use Google's Sign-In script to generate the login button.
tsx// components/GoogleSignIn.tsx
"use client";
import { useEffect } from "react";
import { createClient } from "@/utils/supabase/client";
import Script from "next/script";
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.,
});
(error) {
.(, error);
} {
.(, data);
}
};
(
);
};
;
tsx// pages/login.tsx
import GoogleSignIn from "@/components/GoogleSignIn";
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:
bashNEXT_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.