DEV Community

Anjan Shomodder
Anjan Shomodder

Posted on

How to add Google oAuth in Nextjs with Supabase Auth | Login with Google

This blog will teach you how to add Google oAuth to your Nextjs app with Supabase Auth. I will cover:

  • Setup a Google Cloud project for oAuth
  • How PKCE flow works
  • How to add Google oAuth to your Nextjs app using server actions and components
  • How to get user session data

You can watch the video tutorial here for better understanding.

Setup nextjs with supabase

You can check this blog to learn how to setup nextjs with supabase.

Setup a Google Cloud project for oAuth

  • Go to Google Cloud Console and create a new project.
  • Go to APIs & Services -> OAuth consent screen and fill in the required fields.
    • User Type: External
    • App Name: Your app name
    • User Support Email: Your Email
    • Authorized domains: Supabase Project URL
    • Developer contact information: Your Email
  • Add scopes (first three):
    • email
    • profile
    • openid

Save and go to the dashboard. Then:

  • Go to APIs & Services -> Credentials -> Create Credentials -> OAuth client ID
  • Application type: Web application
  • Name: Your app name
  • Authorized redirect URIs: <domain>/api/auth/callback (eg. http://localhost:3000/api/auth/callback for development)
  • Redirect Uri:
    • Go to supabase dashboard -> Auth -> Providers -> Google
    • Enable and copy the callback url. This is the redirect uri.
  • Click Create and copy the Client ID and Client Secret.

How PKCE flow works

Image description

  • The server creates a secret code and encrypts that code.
  • The server sends the encrypted code to the OAuth server.
  • The OAuth server stores the encrypted code and sends an authorization token to the server.
  • The server sends the authorization token to the client plus the secret code.
  • The OAuth server decrypts and compares the encrypted code with the secret code.
  • If the codes match, the OAuth server sends the access token(JWT) to the server. And now you are logged in.

The secret code is called code_verifier and the encrypted code is called code_challenge.

Create a server action to add google oAuth

  • Create a new file, src/utils/actions.js and add the following code:
'use server'
import { createClientForServer } from '@/utils/supabase/server'
import { redirect } from 'next/navigation'

const signInWith = provider => async () => {
  const supabase = await createClientForServer()

  const auth_callback_url = `${process.env.SITE_URL}/auth/callback`

  const { data, error } = await supabase.auth.signInWithOAuth({
    provider,
    options: {
      redirectTo: auth_callback_url,
    },
  })

  if (error) {
    console.log(error)
  }

  redirect(data.url)
}

const signinWithGoogle = signInWith('google')
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We call the signInWithOAuth method with the provider google and the auth_callback_url.
  • Auth callback url is the url where the user will be redirected after the login. <domain>/auth/callback.
  • We redirect the user to the data.url which is the google login page.

  • Create a new file src/apps/auth/callback/route.js for an api route and add the following code:

import { NextResponse } from 'next/server'
// The client you created from the Server-Side Auth instructions
import { createClientForServer } from '@/utils/supabase/server'

export async function GET(request) {
  const { searchParams, origin } = new URL(request.url)
  const code = searchParams.get('code')
  // if "next" is in param, use it as the redirect URL
  const next = searchParams.get('next') ?? '/'

  if (code) {
    const supabase = await createClientForServer()
    const { error } = await supabase.auth.exchangeCodeForSession(code)
    if (!error) {
      const forwardedHost = request.headers.get('x-forwarded-host') // original origin before load balancer
      const isLocalEnv = process.env.NODE_ENV === 'development'
      if (isLocalEnv) {
        // we can be sure that there is no load balancer in between, so no need to watch for X-Forwarded-Host
        return NextResponse.redirect(`${origin}${next}`)
      } else if (forwardedHost) {
        return NextResponse.redirect(`https://${forwardedHost}${next}`)
      } else {
        return NextResponse.redirect(`${origin}${next}`)
      }
    }
  }

  // return the user to an error page with instructions
  return NextResponse.redirect(`${origin}/auth/auth-code-error`)
}
Enter fullscreen mode Exit fullscreen mode

This code is just copied from the Supabase docs. It exchanges the code for a session and redirects the user to the website. And finally, the user will be logged in.

Now add the UI:

import { signinWithGoogle } from '@/utils/actions'

const Component = () => {
  return (
    <form>
      <button className='btn' formAction={signinWithGoogle}>
        Sign in with Google
      </button>
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

That's it. You have added Google oAuth to your Nextjs app with Supabase Auth. Your app can now access and use user session data.

If you have any questions, feel free to ask in the comments.

I am looking for a new job opportunity. Please feel free to contact me if you or your team are hiring.

Contacts:
Email: thatanjan@gmail.com
Portfolio: https://thatanjan.com/
Linkedin: https://www.linkedin.com/in/thatanjan/
Github: https://github.com/thatanjan/

Next, you can check these videos:



Happy coding! 🚀

Top comments (0)