SimpleAuth
ReactHooks

useGoogleAuth

Hook that wraps auth.signInWithGoogle for custom Google buttons or flows.

Overview

useGoogleAuth wraps auth.signInWithGoogle for custom buttons or flows. Prefer GoogleButton when you want the branded control.

Install

npx @simpleauthjs/react add google-auth

Usage

"use client"

import { useGoogleAuth } from "@/components/simpleauth"

export function MyGoogleLogin() {
  const { signInWithGoogle, isRedirecting, error } = useGoogleAuth()

  return (
    <button type="button" disabled={isRedirecting} onClick={() => signInWithGoogle({ redirectUrl: "https://myapp.com/" })}>
      {isRedirecting ? "Redirecting…" : "Google"}
    </button>
  )
}

Return value

FieldTypeDescription
signInWithGoogle(input: { redirectUrl: string }) => voidStarts the redirect flow.
isRedirectingbooleantrue after click until navigation completes.
errorstring | nullSet when starting the flow throws (e.g. SSR misuse).
isErrorbooleanConvenience flag.
reset() => voidClears local hook state.

Source

components/simpleauth/hooks/use-google-auth.ts
"use client"

import { useState } from "react"
import { SimpleAuthError } from "@simpleauthjs/core"
import { useSimpleAuthClient } from "../provider"

function getErrorMessage(error: unknown) {
  if (error instanceof SimpleAuthError) {
    return error.message
  }

  if (error instanceof Error) {
    return error.message
  }

  return "Unable to start Google sign-in."
}

export function useGoogleAuth() {
  const auth = useSimpleAuthClient()
  const [isRedirecting, setIsRedirecting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  function signInWithGoogle(input: { redirectUrl: string }) {
    setIsRedirecting(true)
    setError(null)

    try {
      auth.signInWithGoogle({ redirectUrl: input.redirectUrl })
    } catch (requestError) {
      setIsRedirecting(false)
      setError(getErrorMessage(requestError))
      throw requestError
    }
  }

  function reset() {
    setError(null)
    setIsRedirecting(false)
  }

  return {
    signInWithGoogle,
    isRedirecting,
    error,
    isError: Boolean(error),
    reset,
  }
}

On this page