Supabase Google Auth: A Next.js Guide

by Jhon Lennon 38 views

Hey guys! Today, we're diving deep into integrating Supabase with Google Auth in a Next.js application. Setting up authentication can be a real headache, but with Supabase and Next.js, it becomes surprisingly straightforward. This comprehensive guide will walk you through each step, ensuring you grasp the underlying concepts and can implement it like a pro. Let's get started!

Why Supabase and Next.js?

Before we get our hands dirty, let’s talk about why Supabase and Next.js are a killer combo. Supabase is an open-source Firebase alternative that provides you with all the backend features you need: databases, authentication, storage, and real-time subscriptions. It's like having your own personal backend-as-a-service (BaaS) but with the flexibility of open source. On the other hand, Next.js is a React framework that enables functionalities like server-side rendering and static site generation. This makes your apps super fast and SEO-friendly. Combining these two gives you a powerful stack for building modern web applications.

Supabase excels in providing a straightforward authentication process. Integrating Google Auth with Supabase simplifies user management, offering a secure and seamless sign-in experience. With Supabase, you don't have to worry about the complexities of managing user credentials or building authentication flows from scratch. This allows you to focus on developing the core features of your application while ensuring robust security. Setting up Google Auth with Supabase involves configuring your Supabase project with Google OAuth credentials, enabling users to sign in using their Google accounts. Supabase handles the backend authentication logic, providing you with user data and session management out of the box. This integration not only enhances security but also improves user experience by providing a familiar and convenient sign-in method.

Next.js offers unparalleled flexibility and performance. Its server-side rendering and static site generation capabilities ensure your application loads quickly and is easily discoverable by search engines. By using Next.js, you can create dynamic user interfaces with React components while optimizing for performance and SEO. Next.js also simplifies the development process by providing features like automatic code splitting, routing, and API route handling. This allows you to build complex applications with ease, without sacrificing performance or scalability. The combination of Next.js and Supabase empowers developers to create modern, high-performance web applications with a streamlined development workflow. With Next.js, you can focus on building the user interface and application logic, while Supabase handles the backend infrastructure and authentication, resulting in a faster and more efficient development process.

Prerequisites

Before jumping into the code, make sure you have the following:

  • Node.js and npm (or yarn): Ensure you have Node.js installed on your machine, as npm (Node Package Manager) comes with it. Yarn is an alternative package manager you can use if you prefer.
  • A Supabase account: Sign up for a free account at supabase.com.
  • A Google Cloud Project: You'll need this to configure Google OAuth.

Having these prerequisites in place will ensure a smooth development process as you integrate Supabase with Google Auth in your Next.js application. With Node.js and npm (or yarn) installed, you'll be able to manage your project's dependencies and run development scripts. A Supabase account provides you with access to the Supabase backend services, including authentication, database, and storage. Creating a Google Cloud Project is necessary to configure Google OAuth, which allows users to sign in to your application using their Google accounts. With these prerequisites, you'll have the necessary tools and resources to follow along with the guide and implement Google Auth with Supabase in your Next.js app. Setting up these prerequisites beforehand ensures that you can focus on the implementation details without encountering any roadblocks along the way. So, let's get these prerequisites sorted out and start building your authentication system!

Step 1: Create a Next.js Project

First things first, let's create a new Next.js project. Open your terminal and run:

npx create-next-app isupabase-google-auth
cd isupabase-google-auth

This sets up a basic Next.js application. If you prefer using yarn, you can use yarn create next-app instead. After creating the project, navigate into the project directory using the cd command. This ensures that all subsequent commands are executed within the context of your Next.js project. With the project created and the terminal pointed to the project directory, you're ready to install the necessary dependencies and start building your authentication system. This initial step is crucial as it sets the foundation for your entire project. By creating a new Next.js project, you're starting with a clean slate, allowing you to structure your application according to best practices and implement the desired features without any conflicts. So, let's get this project created and move on to the next step in integrating Supabase with Google Auth!

Step 2: Install Supabase Client

Next, we need to install the Supabase client library. This library allows your Next.js application to communicate with your Supabase backend. Run the following command in your terminal:

npm install @supabase/supabase-js

Or, if you're using yarn:

yarn add @supabase/supabase-js

This command adds the @supabase/supabase-js package to your project's dependencies. This package provides the necessary functions and tools to interact with your Supabase project, including authentication, database queries, and real-time subscriptions. Once the installation is complete, you can import the Supabase client into your Next.js components and start using it to authenticate users, fetch data, and perform other backend operations. Installing the Supabase client library is a crucial step in integrating Supabase with your Next.js application. Without this library, your application won't be able to communicate with your Supabase backend, making it impossible to implement authentication or access your database. So, make sure to install the Supabase client library before proceeding to the next steps in the guide. With the Supabase client library installed, you'll have the necessary tools to build a seamless integration between your Next.js frontend and Supabase backend, allowing you to create dynamic and data-driven web applications.

Step 3: Set Up Supabase Project

Now, let's configure our Supabase project. Go to your Supabase dashboard and create a new project. Once your project is set up, navigate to Settings > API. Here, you’ll find your Supabase URL and Supabase Anon Key. These are essential for connecting your Next.js app to your Supabase backend. Make sure to keep these keys secure and do not expose them in your client-side code.

Setting up your Supabase project involves creating a new project on the Supabase platform and configuring it with the necessary settings. Once your project is created, you'll need to navigate to the API settings to retrieve your Supabase URL and Supabase Anon Key. These keys are crucial for authenticating your Next.js application with your Supabase backend. The Supabase URL is the endpoint where your Supabase project is hosted, while the Supabase Anon Key is a public key that allows your application to access your Supabase resources. It's important to handle these keys with care and avoid exposing them in your client-side code. Instead, store them in environment variables and access them from your server-side code. With your Supabase project set up and your keys retrieved, you're ready to configure your Next.js application to connect to your Supabase backend. This involves creating a Supabase client instance with your Supabase URL and Supabase Anon Key, which you'll use to authenticate users, fetch data, and perform other backend operations. Setting up your Supabase project is a critical step in integrating Supabase with your Next.js application. Without a properly configured Supabase project, your application won't be able to access the Supabase backend, making it impossible to implement authentication or access your database.

Step 4: Configure Google OAuth

To enable Google authentication, you need to set up Google OAuth. Follow these steps:

  1. Go to the Google Cloud Console: Head over to console.cloud.google.com.
  2. Create a New Project: If you don't have one already, create a new project.
  3. Enable the Google Sign-In API: In the API Library, search for "Google Sign-In API" and enable it.
  4. Create OAuth 2.0 Credentials:
    • Go to Credentials and click Create Credentials > OAuth client ID.
    • Select Web application as the application type.
    • Give it a name, like "Next.js App".
    • In the Authorized JavaScript origins, add http://localhost:3000 (for development) and your production URL.
    • In the Authorized redirect URIs, add http://localhost:3000/api/auth/callback/google (for development) and your production URL.
  5. Get Your Client ID and Client Secret: After creating the credentials, you'll get a Client ID and Client Secret. Store these securely.

Configuring Google OAuth involves several steps, starting with creating a new project in the Google Cloud Console. If you don't already have a project, you'll need to create one to proceed. Once you have a project, you'll need to enable the Google Sign-In API, which allows users to sign in to your application using their Google accounts. To do this, navigate to the API Library in the Google Cloud Console, search for "Google Sign-In API," and enable it. Next, you'll need to create OAuth 2.0 credentials for your application. To do this, go to the Credentials section in the Google Cloud Console and click Create Credentials > OAuth client ID. Select Web application as the application type and give it a name, such as "Next.js App." In the Authorized JavaScript origins field, add http://localhost:3000 for development and your production URL. In the Authorized redirect URIs field, add http://localhost:3000/api/auth/callback/google for development and your production URL. After creating the credentials, you'll receive a Client ID and Client Secret. It's crucial to store these securely and avoid exposing them in your client-side code. Instead, store them in environment variables and access them from your server-side code. With your Google OAuth credentials configured, you're ready to integrate Google Auth with your Supabase project. This involves configuring your Supabase project with your Google Client ID and Client Secret, allowing users to sign in to your application using their Google accounts.

Step 5: Set Up Environment Variables

Now, let's set up our environment variables. Create a .env.local file in the root of your project and add the following:

NEXT_PUBLIC_SUPABASE_URL=YOUR_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
GOOGLE_CLIENT_ID=YOUR_GOOGLE_CLIENT_ID
GOOGLE_CLIENT_SECRET=YOUR_GOOGLE_CLIENT_SECRET

Replace YOUR_SUPABASE_URL, YOUR_SUPABASE_ANON_KEY, YOUR_GOOGLE_CLIENT_ID, and YOUR_GOOGLE_CLIENT_SECRET with your actual values. Remember to prefix SUPABASE_URL and SUPABASE_ANON_KEY with NEXT_PUBLIC_ to make them accessible in your client-side code. However, it's crucial to keep GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET secure and only accessible on the server side to prevent unauthorized access.

Setting up environment variables is a crucial step in configuring your Next.js application to connect to your Supabase backend and integrate with Google Auth. Environment variables allow you to store sensitive information, such as API keys and database credentials, separately from your code. This ensures that your sensitive information is not exposed in your codebase, which can be a security risk. To set up environment variables, create a .env.local file in the root of your project and add the necessary variables. In this case, you'll need to add NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY, GOOGLE_CLIENT_ID, and GOOGLE_CLIENT_SECRET. Replace the placeholder values with your actual Supabase URL, Supabase Anon Key, Google Client ID, and Google Client Secret. It's important to prefix SUPABASE_URL and SUPABASE_ANON_KEY with NEXT_PUBLIC_ to make them accessible in your client-side code. However, you should avoid exposing GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in your client-side code, as this can be a security risk. Instead, access these variables from your server-side code. With your environment variables set up, you can access them in your Next.js components and API routes using the process.env object. This allows you to configure your application without hardcoding sensitive information in your code.

Step 6: Create API Route for Google Sign-In

Next, create an API route to handle the Google sign-in callback. Create a file named pages/api/auth/callback/google.js with the following content:

import { supabase } from '../../../../utils/supabaseClient'

export default async function handler(req, res) {
  const { code } = req.query

  if (code) {
    try {
      const { error } = await supabase.auth.exchangeCodeForSession(code)
      if (error) throw error

      res.redirect('/')
    } catch (error) {
      console.error('Error exchanging code for session:', error)
      res.status(500).json({ error: error.message })
    }
  }
}

This API route handles the callback from Google after a user successfully authenticates. It exchanges the authorization code for a Supabase session and redirects the user to the home page.

Creating an API route for Google sign-in involves creating a new file in the pages/api directory of your Next.js project. This file will handle the callback from Google after a user successfully authenticates. The API route should export an asynchronous function that takes two arguments: req (the request object) and res (the response object). Inside the function, you'll need to extract the authorization code from the request query parameters. This code is provided by Google after the user grants permission to your application to access their Google account. Once you have the authorization code, you can exchange it for a Supabase session using the supabase.auth.exchangeCodeForSession method. This method sends a request to the Supabase backend, which verifies the authorization code and returns a session object containing the user's information. If the exchange is successful, you can redirect the user to the home page or any other page in your application. If there's an error during the exchange, you should log the error and return an error response to the client. This helps you debug any issues with the authentication process. The API route should be protected to prevent unauthorized access. You can use middleware to verify the request and ensure that it's coming from a trusted source. With your API route set up, you're ready to integrate Google Auth with your Next.js application. Users can sign in to your application using their Google accounts, and the authentication process will be handled seamlessly by Supabase.

Step 7: Create a Supabase Client

Create a file to initialize the Supabase client. In utils/supabaseClient.js:

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY

export const supabase = createClient(supabaseUrl, supabaseAnonKey)

This initializes the Supabase client with your Supabase URL and Anon Key, making it easy to use throughout your application.

Creating a Supabase client involves creating a new file in your project to initialize the Supabase client library. This file will contain the code that creates a new instance of the Supabase client, which you'll use to interact with your Supabase backend. To create a Supabase client, you'll need to import the createClient function from the @supabase/supabase-js package. This function takes two arguments: your Supabase URL and your Supabase Anon Key. Your Supabase URL is the endpoint where your Supabase project is hosted, while your Supabase Anon Key is a public key that allows your application to access your Supabase resources. You can retrieve these values from your Supabase dashboard. Once you have your Supabase URL and Anon Key, you can create a new instance of the Supabase client by calling the createClient function with these values. You should store the Supabase client instance in a variable, such as supabase, and export it so that you can use it in other parts of your application. This makes it easy to access the Supabase client from any component or API route in your project. With your Supabase client created, you're ready to start using it to authenticate users, fetch data, and perform other backend operations. You can use the Supabase client to interact with your Supabase database, storage, and authentication services. This allows you to build a seamless integration between your Next.js frontend and Supabase backend, enabling you to create dynamic and data-driven web applications.

Step 8: Implement Google Sign-In in Your Component

Now, let's implement the Google sign-in functionality in one of your components. For example, in pages/index.js:

import { supabase } from '../utils/supabaseClient'
import { useEffect, useState } from 'react'

export default function Home() {
  const [session, setSession] = useState(null)

  useEffect(() => {
    supabase.auth.getSession().then(({ data: { session } }) => {
      setSession(session)
    })

    supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session)
    })
  }, [])

  return (
    
      <h1>Supabase Google Auth with Next.js</h1>
      
        {session ? (
          
            <p>Signed in: {session.user.email}</p>
            <button onClick={() => supabase.auth.signOut()}>Sign out</button>
          
        ) : (
          <button onClick={() => supabase.auth.signInWithOAuth({ provider: 'google' })}>Sign in with Google</button>
        )}
      
    
  )
}

This component checks if the user is signed in and displays either a sign-in button or the user's email and a sign-out button.

Implementing Google sign-in in your component involves adding the necessary code to handle user authentication with Google. To do this, you'll need to import the Supabase client and the useState and useEffect hooks from React. The useState hook allows you to manage the user's session state, while the useEffect hook allows you to perform side effects, such as fetching the user's session from Supabase. In your component, you'll need to create a state variable to store the user's session. You can use the useState hook to create this variable, initializing it to null. Then, in a useEffect hook, you'll need to fetch the user's session from Supabase using the supabase.auth.getSession method. This method returns a promise that resolves with the user's session object. Once you have the session object, you can update the state variable with the user's session. You'll also need to set up a listener for authentication state changes using the supabase.auth.onAuthStateChange method. This method allows you to detect when the user signs in or signs out of your application. When the authentication state changes, you can update the state variable with the new session. In your component's render method, you'll need to display either a sign-in button or the user's email and a sign-out button, depending on whether the user is signed in or not. If the user is not signed in, you can display a sign-in button that calls the supabase.auth.signInWithOAuth method when clicked. This method redirects the user to Google's authentication page, where they can sign in with their Google account. If the user is signed in, you can display the user's email and a sign-out button that calls the supabase.auth.signOut method when clicked. This method signs the user out of your application and redirects them to the home page.

Conclusion

And there you have it! You've successfully integrated Supabase with Google Auth in your Next.js application. This setup provides a secure and streamlined authentication experience for your users. By following these steps, you can focus on building amazing features without worrying about the complexities of authentication. Happy coding!

Integrating Supabase with Google Auth in your Next.js application provides a secure and streamlined authentication experience for your users. By following the steps outlined in this guide, you can focus on building amazing features without worrying about the complexities of authentication. This setup not only enhances security but also improves user experience by providing a familiar and convenient sign-in method. With Supabase handling the backend authentication logic and Next.js providing the flexibility and performance of React, you can create modern, high-performance web applications with ease. This integration allows you to focus on building the user interface and application logic, while Supabase handles the backend infrastructure and authentication, resulting in a faster and more efficient development process. By leveraging the power of Supabase and Next.js, you can create dynamic and data-driven web applications with a seamless user experience. The combination of Supabase's authentication capabilities and Next.js's rendering and routing features empowers developers to build robust and scalable web applications with a streamlined development workflow. So, go ahead and start building your authentication system with Supabase and Next.js, and create amazing applications that your users will love!