SimpleAuth
ReactHooks

useGithubAuth

Hook that wraps auth.signInWithGithub for custom GitHub buttons or flows.

Overview

useGithubAuth wraps auth.signInWithGithub for custom buttons or flows. Prefer GithubButton when you want the branded control.

Install

npx @simpleauthjs/react add github-auth

Usage

"use client"

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

export function MyGithubLogin() {
  const { signInWithGithub, isRedirecting, error } = useGithubAuth()

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

Return value

FieldTypeDescription
signInWithGithub(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-github-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 GitHub sign-in."
}

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

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

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

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

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

On this page