OWolf

2024-10-15 Web Development

How to Enable Google Auth for Supabase in a Next.js App

By 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.


1. Supabase Setup

a. Enable Google Provider in Supabase

  1. Go to your Supabase dashboard.
  2. Navigate to Authentication > Providers.
  3. Enable Google Sign-In by toggling the Google provider.
  4. You'll need the Client ID and Client Secret from Google (explained in the next section) to complete the setup.
  5. Copy the Callback URL from the Supabase dashboard (it looks like https://<your-supabase-url>.supabase.co/auth/v1/callback).

b. Set Up OAuth Credentials in Supabase

  • Once you obtain the Google Client ID and Client Secret, enter them in the Google provider section of the Supabase dashboard.

2. Google Cloud Setup

a. Create a Project in Google Cloud

  1. Go to Google Cloud Console.
  2. Create a new project (or use an existing one).

b. Configure OAuth Consent Screen

  1. In the OAuth consent screen section, configure the consent screen (app name, privacy policy, etc.).
  2. Add your Supabase domain (<your-supabase-url>.supabase.co) to Authorized Domains.

c. Create OAuth 2.0 Credentials

  1. Navigate to API & Services > Credentials.
  2. Click Create Credentials > OAuth Client ID.
  3. Set the Application Type to Web application.
  4. Under Authorized JavaScript Origins, add your Next.js app’s URLs:
    • Example for production: https://your-nextjs-app.com
    • Example for local development: http://localhost:3000
  5. Under Authorized Redirect URIs, add your Supabase callback URL from Step 1.
  6. Click Create and note down the Client ID and Client Secret.

3. Next.js Setup

a. Install Supabase Client

  1. Install Supabase client in your Next.js project:
    bash
    npm install @supabase/supabase-js
    

b. Google Sign-In Component

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.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;

c. Integrate the GoogleSignIn Component in Your Login Page

tsx
// pages/login.tsx
import GoogleSignIn from "@/components/GoogleSignIn";

export default function LoginPage() {
  return (
    <div>
      <h1>Login to Your App</h1>
      <GoogleSignIn />
    </div>
  );
}

d. Environment Variables

Ensure you have the correct environment variables in your Next.js app:

bash
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.


Conclusion

  1. In Supabase: Enable the Google provider, set up OAuth credentials.
  2. In Google Cloud: Create a project, configure OAuth credentials, and set up authorized URLs.
  3. In Next.js: Use the Supabase client and Google Sign-In script to handle user authentication.

With these steps, you can easily integrate Google authentication in your Next.js app with Supabase.