Docs

useOAuth()

The useOAuth() hook is used to create a new OAuth flow. It can be used in both web and native apps.

Parameters

  • Name
    strategy
    Type
    OAuthStrategy
    Description

    The strategy corresponding to the OAuth provider. For example: oauth_facebook, oauth_github, etc.

  • Name
    redirectUrl?
    Type
    string
    Description

    The URL or path to redirect to after the OAuth flow is complete.

  • Name
    unsafeMetadata?
    Type
    SignUpUnsafeMetadata
    Description

    Unsafe metadata to be passed to the OAuth provider.

Returns

The useOAuth() hook returns the startOAuthFlow() method, which you can use to initiate the OAuth flow.

The startOAuthFlow() method has the following signature:

const startOAuthFlow: (
  startOAuthFlowParams?: StartOAuthFlowParams,
) => Promise<StartOAuthFlowReturnType>

It accepts the following parameters (StartOAuthFlowParams):

  • Name
    redirectUrl?
    Type
    string
    Description

    The URL or path to redirect to after the OAuth flow is complete.

  • Name
    unsafeMetadata?
    Type
    SignUpUnsafeMetadata
    Description

    Unsafe metadata to be passed to the OAuth provider.

The following example demonstrates how to create a custom OAuth sign-in flow for Google accounts.

app/(auth)/sign-in.tsx
import React from 'react'
import * as WebBrowser from 'expo-web-browser'
import { Text, View, Button } from 'react-native'
import { Link } from 'expo-router'
import { useOAuth } from '@clerk/clerk-expo'
import * as Linking from 'expo-linking'

export const useWarmUpBrowser = () => {
  React.useEffect(() => {
    // Warm up the android browser to improve UX
    // https://docs.expo.dev/guides/authentication/#improving-user-experience
    void WebBrowser.warmUpAsync()
    return () => {
      void WebBrowser.coolDownAsync()
    }
  }, [])
}

WebBrowser.maybeCompleteAuthSession()

export default function Page() {
  useWarmUpBrowser()

  const { startOAuthFlow } = useOAuth({ strategy: 'oauth_google' })

  const onPress = React.useCallback(async () => {
    try {
      const { createdSessionId, signIn, signUp, setActive } = await startOAuthFlow({
        redirectUrl: Linking.createURL('/dashboard', { scheme: 'myapp' }),
      })

      // If sign in was successful, set the active session
      if (createdSessionId) {
        setActive!({ session: createdSessionId })
      } else {
        // Use signIn or signUp returned from startOAuthFlow
        // for next steps, such as MFA
      }
    } catch (err) {
      // See https://clerk.com/docs/custom-flows/error-handling
      // for more info on error handling
      console.error(JSON.stringify(err, null, 2))
    }
  }, [])

  return (
    <View>
      <Link href="/">
        <Text>Home</Text>
      </Link>
      <Button title="Sign in with Google" onPress={onPress} />
    </View>
  )
}

Feedback

What did you think of this content?

Last updated on