Skip to main content

@privy-io/react-auth

Classes

Interfaces

Type Aliases

CallbackError

Ƭ CallbackError: (error: PrivyErrorCode) => void

Type declaration

▸ (error): void

Parameters
NameType
errorPrivyErrorCode
Returns

void


ContractUIOptions

Ƭ ContractUIOptions: Object

If the transaction to be sent is a call to a smart contract, you may use this object to fill in additional details about the contract being called.

Type declaration

NameTypeDescription
actionText?stringDeprecated Use description in SendTransactionModalUIOptions instead.
imgAltText?stringAlt text for the image in the Send Transaction screen, if a valid imgUrl is set.
imgSize?"sm" | "lg"Size for the image in the Send Transaction screen, if a valid imgUrl is set.
imgUrl?stringURL for an image to show in the Send Transaction screen.
name?stringName of smart contract being called.
url?stringURL with more information about the smart contract.

FundWalletConfig

Ƭ FundWalletConfig: Object

Optional configuration parameter for the fiat on-ramp.

Type declaration

NameType
configMoonpayConfig
provider?"moonpay"

MfaMethod

Ƭ MfaMethod: typeof SUPPORTED_MFA_METHODS[number]


MoonpayConfig

Ƭ MoonpayConfig: Object

Configuration parameter for the MoonPay fiat on-ramp.

Type declaration

NameType
currencyCode?MoonpayCurrencyCode
paymentMethod?MoonpayPaymentMethod
quoteCurrencyAmount?number
uiConfig?{ accentColor?: string ; theme?: "light" | "dark" }
uiConfig.accentColor?string
uiConfig.theme?"light" | "dark"

MoonpayCurrencyCode

Ƭ MoonpayCurrencyCode: "AVAX_CCHAIN" | "CELO_CELO" | "CUSD_CELO" | "DAI_ETHEREUM" | "ETH_ETHEREUM" | "ETH_ARBITRUM" | "ETH_POLYGON" | "ETH_BASE" | "FIL_FVM" | "MATIC_ETHEREUM" | "MATIC_POLYGON" | "USDC_ETHEREUM" | "USDC_ARBITRUM" | "USDC_OPTIMISM" | "USDC_POLYGON" | "USDC_BASE" | "USDT_ETHEREUM" | "USDT_POLYGON" | "WETH_POLYGON" | "WBTC_ETHEREUM" | "BNB_BNB" | "BNB_BSC"

Cryptocurrency codes for the MoonPay fiat on-ramp. These codes follow the format {TOKENNAME}{NETWORK_NAME}.


MoonpayPaymentMethod

Ƭ MoonpayPaymentMethod: "ach_bank_transfer" | "credit_debit_card" | "gbp_bank_transfer" | "gbp_open_banking_payment" | "mobile_wallet" | "sepa_bank_transfer" | "sepa_open_banking_payment" | "pix_instant_payment" | "yellow_card_bank_transfer"

Accepted payment methods for the MoonPay fiat on-ramp.


PriceDisplayOptions

Ƭ PriceDisplayOptions: { primary: "fiat-currency" ; secondary: "native-token" } | { primary: "native-token" ; secondary: null }

Options to customize the display of transaction prices in the embedded wallet's transaction prompt.


PrivyClientConfig

Ƭ PrivyClientConfig: Object

Type declaration

NameTypeDescription
additionalChains?Chain[]Deprecated use supportedChains instead.
appearance?{ accentColor?: HexColor ; logo?: string | ReactElement ; showWalletLoginFirst?: boolean ; theme?: "light" | "dark" | HexColor }All UI and theme related configuration
appearance.accentColor?HexColorAccent color for the privy UI. Used for buttons, active borders, etc. This will generate light and dark variants. This overrides the server setting accent_color.
appearance.logo?string | ReactElementLogo for the main privy modal screen. This can be a string (url) or an img / svg react element. If passing an element, Privy will overwrite the style props, to ensure proper rendering. This overrides the server setting logo_url
appearance.showWalletLoginFirst?booleanDetermines the order of the login options in the privy modal. If true, the wallet login will render above social and email / sms login options. This overrides the server setting show_wallet_login_first
appearance.theme?"light" | "dark" | HexColorPrimary theme for the privy UI. This dictates the foreground and background colors within the UI. 'light' (default): The privy default light UI. 'dark': The privy default dark UI. custom hex code (i.e. '#13152F'): A custom background. This will generate the remainder of the foreground and background colors for the UI by modulating the luminance of the passed color. This value should be either dark or light (<20% or >80% luminance), for accessibility.
captchaEnabled?boolean-
customAuth?{ enabled?: boolean ; getCustomAccessToken: () => Promise<string | undefined> ; isLoading: boolean }This property is only required for apps that use a third-party authentication provider.
customAuth.enabled?booleanIf true, enable custom authentication integration. This enables a JWT from a custom auth provider to be used to authenticate Privy embedded wallets. Defaults to true. Default ts true
customAuth.getCustomAccessToken() => Promise<string | undefined>A callback that returns the user's custom auth provider's access token as a string. Can be left blank if using cookies to store and send access tokens Example ts const {getAccessTokenSilently} = useAuth(); <PrivyProvider {...props} config={{ customAuth: { getCustomAccessToken: getAccessTokenSilently }, }} />
customAuth.isLoadingbooleanCustom auth providers loading state Example ts const {isLoading} = useAuth(); <PrivyProvider {...props} config={{ customAuth: { isLoading, }, }} />
defaultChain?ChainWhen supplied, the defaultChain will be the default chain used throughout the application. For external wallets, it will be used if the user's wallet it not within the supportedChains (or default chains) list. For embedded wallets, it will be used upon initialization, when the user hasn't switched to another supported chain.
embeddedWallets?{ createOnLogin?: EmbeddedWalletCreateOnLoginConfig ; noPromptOnSignature?: boolean ; priceDisplay?: PriceDisplayOptions ; requireUserPasswordOnCreate?: boolean ; waitForTransactionConfirmation?: boolean }All embedded wallets configuration
embeddedWallets.createOnLogin?EmbeddedWalletCreateOnLoginConfigWhether an embedded wallet should be created for the user on login. This overrides the deprecated createPrivyWalletOnLogin. For all-users, the user will be prompted to create a Privy wallet after successfully logging in. If they cancel or are visiting after this flag was put in place, they will be prompted to create a wallet on their next login. For users-without-wallets, the user will be prompted to create a Privy wallet after\ successfully logging in, only if they do not currently have any wallet associated with their user object - for example if they have linked an external wallet. For off, an embedded wallet is not created during login. You can always prompt the user to create one manually with your app. Defaults to 'off'.
embeddedWallets.noPromptOnSignature?booleanIf true, Privy will not prompt or instantiate any UI for embedded wallet signatures and transactions. If false, embedded wallet actions will raise a modal and require user confirmation to proceed. Defaults to false.
embeddedWallets.priceDisplay?PriceDisplayOptionsOptions to customize the display of transaction prices in the embedded wallet's transaction prompt. You may configure a primary currency to emphasize, and a secondary currency to show as subtext. Defaults to emphasizing the price in fiat currency, and showing the price in the native token as subtext. You may either set: - {primary: 'fiat-currency', secondary: 'native-token'} to emphasize fiat currency prices, showing native token prices as subtext. This is the default. - {secondary: 'native-token', secondary: null} to show native token prices only, with no subtext. Privy does not currently support: - emphasizing native token prices over fiat currency prices - showing prices only in fiat currency, without native token prices
embeddedWallets.requireUserPasswordOnCreate?booleanIf true, Privy will prompt users to create a password for their Privy embedded wallet. If false, embedded wallets will be created without the need of password. Defaults to false.
embeddedWallets.waitForTransactionConfirmation?booleanThis setting is only honored when using the EIP-1193 Ethereum Provider to interface with the embedded wallet, i.e. using getEthereumProvider or getEthersProvider. This setting is only honored when used alongside noPromptOnSignature: true If true, calls to sendTransaction will wait for the transaction to be confirmed before resolving. If false, calls to sendTransaction will resolve once the transaction has been submitted. Defaults to true. Example ts <PrivyProvider config={{ embeddedWallets: { noPromptOnSignature: true, waitForTransactionConfirmation: false, }, }} > {children} </PrivyProvider>
fiatOnRamp?{ useSandbox?: boolean }Setting associated with fiat-on-ramp flows
fiatOnRamp.useSandbox?booleanDetermines whether to use the sandbox flow. Defaults to false.
legal?{ privacyPolicyUrl?: string | null ; termsAndConditionsUrl?: string | null }All legal configuration
legal.privacyPolicyUrl?string | nullURL to the privacy policy page for your application. Rendered as a link in the privy modal footer. This overrides the server setting privacy_policy_url
legal.termsAndConditionsUrl?string | nullURL to the terms and conditions page for your application. Rendered as a link in the privy modal footer. This overrides the server setting terms_and_conditions_url
loginMethods?("wallet" | "email" | "sms" | "google" | "twitter" | "discord" | "github" | "linkedin" | "tiktok" | "apple")[]Specified login methods for the privy modal. If this parameter is included, it will override any login method settings specified on the server. Only email OR sms can be specified, not both. If both are specified, email will be used. Social login methods require email OR sms to also be specified. loginMethods cannot be an empty array if specified. The order of this array does not currently dictate order of the login methods in the UI, but may in the future.
supportedChains?Chain[]A list of supported chains, used to specify which chains should be used throughout the application. Calling sendTransaction or switchChain on an unsupported network will throw an error. For external wallets, if the wallet's current chain post-connection (during connect-only or siwe flows) is not within the supported chains list, the user will be prompted to switch to the defaultChain (if set) or first supplied supportedChain. If the chain switching process does not fully succeed, the user will not be blocked from the application (and the wallet's current chainId can always be observed and acted upon accordingly.) For embedded wallets, the wallet will automatically default to the defaultChain (if set) or first supplied supportedChain.
walletConnectCloudProjectId?string-

PrivyEvents

Ƭ PrivyEvents: Object

Type declaration

NameType
configureMfa{ onError?: CallbackError ; onMfaRequired: (mfaMethods: MfaMethod[]) => void }
configureMfa.onError?CallbackError
configureMfa.onMfaRequired(mfaMethods: MfaMethod[]) => void
connectWallet{ onError?: CallbackError ; onSuccess?: (wallet: BaseConnectedWallet) => void }
connectWallet.onError?CallbackError
connectWallet.onSuccess?(wallet: BaseConnectedWallet) => void
createWallet{ onError?: CallbackError ; onSuccess?: (wallet: Wallet) => void }
createWallet.onError?CallbackError
createWallet.onSuccess?(wallet: Wallet) => void
login{ onComplete?: (user: User, isNewUser: boolean, wasAlreadyAuthenticated: boolean) => void ; onError?: CallbackError }
login.onComplete?(user: User, isNewUser: boolean, wasAlreadyAuthenticated: boolean) => void
login.onError?CallbackError
logout{ onSuccess?: () => void }
logout.onSuccess?() => void

Quantity

Ƭ Quantity: string | number | bigint


SendTransactionModalUIOptions

Ƭ SendTransactionModalUIOptions: Object

UI customization object for the embedded wallet's Send Transaction screen

Type declaration

NameTypeDescription
buttonText?stringText to show on CTA button for Send Transaction screen. Defaults to 'Submit'.
description?stringDescription of the transaction being sent.
header?stringText to display at top of Send Transaction screen. Defaults to 'Review transaction' or 'Send (insert token symbol)' if transaction is a simple token transfer.
modalTitle?stringDeprecated Use header instead.
senderInfo?ContractUIOptionsDeprecated Use transactionInfo.contractInfo instead.
title?stringDeprecated Use header instead.
transactionInfo?TransactionUIOptionsDetails about the transaction that the user will send. Will be shown in an accordion in the Send Transaction screen.

SignMessageModalUIOptions

Ƭ SignMessageModalUIOptions: Object

UI configuration object for the embedded wallet's Sign Message screen

Type declaration

NameTypeDescription
buttonText?stringText for the CTA button on the Sign Message screen. Defaults to 'Sign and Continue'
description?stringDescription text for the Sign Message screen. Defaults to 'Sign to continue'.
title?stringTitle for the Sign Message screen. Defaults to 'Sign'.

TransactionLog

Ƭ TransactionLog: Object

Type declaration

NameType
addressstring
blockHashstring
blockNumbernumber
datastring
logIndexnumber
removedboolean
topicsstring[]
transactionHashstring
transactionIndexnumber

TransactionReceipt

Ƭ TransactionReceipt: Object

Type declaration

NameType
blockHashstring
blockNumbernumber
byzantiumboolean
confirmationsnumber
contractAddressstring
cumulativeGasUsedstring
effectiveGasPrice?string
fromstring
gasUsedstring
logsTransactionLog[]
logsBloomstring
root?string
status?number
tostring
transactionHashstring
transactionIndexnumber
typenumber

TransactionUIOptions

Ƭ TransactionUIOptions: Object

UI customization object for additional transaction details. Will be shown in an expandable accordion in the Send Transaction screen.

Type declaration

NameTypeDescription
action?stringAction that the user is taking when sending this transaction. This should be short (<4 words, e.g. 'Buy NFT'). Will be shown inside the transaction details accordion in Send Transaction screen.
actionDescription?stringDeprecated Use title instead.
contractInfo?ContractUIOptionsIf the transaction to be sent is a call to a smart contract, you may use this object to fill in additional details about the contract being called.
description?stringDeprecated Use description in SendTransactionModalUIOptions instead.
title?stringTitle for the transaction details accordion within the Send Transaction screen. Defaults to 'Details'.

UnsignedTransactionRequest

Ƭ UnsignedTransactionRequest: Object

Type declaration

NameType
accessList?{ address: string ; storageKeys: string[] }[] | [string, string[]][] | Record<string, string[]>
chainId?number
data?ArrayLike<number> | string
from?string
gasLimit?Quantity
gasPrice?Quantity
maxFeePerGas?Quantity
maxPriorityFeePerGas?Quantity
nonce?Quantity
to?string
type?number
value?Quantity

Variables

SUPPORTED_CHAINS

Const SUPPORTED_CHAINS: readonly [Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain, Chain]


VERSION

Const VERSION: string = version

Functions

Captcha

Captcha(props): null | Element

Used to render an invisible captcha alongside important forms

Notes:

  • Only for internal use, or use with headless SDK (the Privy modal handles captchas internally with this component)
  • Only one <Captcha /> should be rendered at a time, since it injects/removes a global script
  • the state of the captcha workflow can be accessed using useCaptcha
  • wrapper around marsidev/react-turnstile, accepts same props

Parameters

NameType
propsPartial<TurnstileProps>

Returns

null | Element


PrivyProvider

PrivyProvider(«destructured»): Element

Passes the Privy authentication context to your React components.

This should wrap any components that will to use the Privy SDK via the usePrivy hook. As an example:

// At your application root (e.g. `_app.tsx` in NextJS):
import {PrivyProvider} from '@privy-io/react-auth';

<PrivyProvider appId="APP_ID_FROM_CONSOLE" onSuccess={() => console.log('Success!')}>
<Component {...pageProps} />
</PrivyProvider>

Parameters

NameType
«destructured»PrivyProviderProps

Returns

Element


errorIndicatesMaxMfaRetries

errorIndicatesMaxMfaRetries(error): error is PrivyIframeError

Parameters

NameType
errorunknown

Returns

error is PrivyIframeError


errorIndicatesMfaTimeout

errorIndicatesMfaTimeout(error): error is PrivyIframeError

Parameters

NameType
errorunknown

Returns

error is PrivyIframeError


errorIndicatesMfaVerificationFailed

errorIndicatesMfaVerificationFailed(error): error is PrivyIframeError

Parameters

NameType
errorunknown

Returns

error is PrivyIframeError


getAccessToken

getAccessToken(): Promise<string | null>

Returns

Promise<string | null>


useConnectWallet

useConnectWallet(callbacks?): Object

Use this hook to connect the user's external wallet, and to attach callbacks after a user succesfully connects their wallet, or if there is an error during the connection attempt.

Parameters

NameTypeDescription
callbacks?Object-
callbacks.onError?CallbackErrorCallback that will execute in the case of a non-successful wallet connection. Param PrivyErrorCode - the corresponding error code
callbacks.onSuccess?(wallet: BaseConnectedWallet) => voidCallback that will execute once a successful connectWallet completes. This will not run in the case of a wallet-based authentication flow.

Returns

Object

connectWallet - opens the Privy modal and prompts the user to connect an external wallet

NameType
connectWallet() => void

useCreateWallet

useCreateWallet(callbacks?): Object

Use this hook to create a privy wallet for a user, and to attach a callback after successful wallet creation.

Parameters

NameTypeDescription
callbacks?Object-
callbacks.onError?CallbackErrorCallback that will execute in the case of a non-successful wallet creation. Param {PrivyErrorCode} - the corresponding error code
callbacks.onSuccess?(wallet: Wallet) => voidCallback that will execute once on a successful embedded wallet creation. This will run when createWallet is called manually, or when config.embeddedWallets.createOnLogin triggers an automatic wallet creation.

Returns

Object

createWallet - creates a privy wallet for the user.

NameType
createWallet() => Promise<Wallet>

useLogin

useLogin(callbacks?): Object

Use this hook to log the user in, and to attach callbacks for successful logins, already-authenticated users, and login errors.

Parameters

NameTypeDescription
callbacks?Object-
callbacks.onComplete?(user: User, isNewUser: boolean, wasAlreadyAuthenticated: boolean) => voidCallback that will execute once a login flow successfully completes. - If config.embeddedWallets.createOnLogin is set to 'off' or a wallet creation flow is not applicable, this will run after the user successfully authenticates. - If config.embeddedWallets.createOnLogin is set to 'users-without-wallets' or 'all-users', this will run after the user successfully authenticates and creates their wallet (if applicable). - If a user is already authenticated, this will run immediately and the wasAlreadyAuthenticated flag will be set to true.
callbacks.onError?CallbackErrorCallback that will execute in the case of a non-successful login. Param PrivyErrorCode - the corresponding error code

Returns

Object

login - opens the Privy modal and prompts the user to login

NameType
login() => void

useLoginWithEmail

useLoginWithEmail(): UseLoginWithEmail

Use this hook to log the user in with email, without using any Privy UIs.

Returns

UseLoginWithEmail

sendCode - sendCode sends a one-time-code to the user's email address.

loginWithCode - loginWithCode - logs a user in with a one-time-code, maximum 5 attempts.


useLogout

useLogout(callbacks?): Object

Use this hook to log the user out, and to attach a callback after a successful logout.

Parameters

NameType
callbacks?Object
callbacks.onSuccess?() => void

Returns

Object

logout - logs the user out and clears their authentication state.

NameType
logout() => Promise<void>

useMfa

useMfa(): Object

Use this hook to execute the MFA flow with Privy.

Returns

Object

init - starts the MFA verification flow

submit - completes the MFA verification flow

cancel - cancels the MFA verification flow

NameType
cancel() => void
init(mfaMethod: "sms" | "totp") => Promise<void>
submit(mfaMethod: "sms" | "totp", mfaCode: string) => Promise<void>

Example

// MFA flow

const MFAModal = ({ mfaMethods, isOpen, setIsOpen }: Props) => {
const {init, submit, cancel} = useMfa();
const [selectedMethod, setSelectedMethod] = useState(null)
const [mfaCode, setMfaCode] = useState('')

const handleClose = () => {
cancel();
setIsOpen(false);
};

return (
<Modal isOpen={isOpen} onClose={handleClose}>
// Capture the user's MFA code
{selectedMethod && (
<button
onClick={async () => {
await submit(selectedMethod, mfsCode)
setSelectedMethod(null)
setIsOpen(false)
}}
/>
)}
{mfaMethods.map(method => (
<button
onClick={async () => {
await init(method);
setSelectedMethod(method)
}}
>
Choose {method} for MFA
</button>
))}
</Modal>
)
};

Example

// Error handling

import {
errorIndicatesMfaVerificationFailed,
errorIndicatesMfaTimeout,
errorIndicatesMfaMaxAttempts
} from '@privy-io/react-auth';
const {submit} = useMfa();
const [errorState, setErrorState] = useState<string | null>(null);

<button
onClick={async () => {
try {
submit('sms', '<user-mfa-code>');
}
catch (e) {
if (errorIndicatesMfaVerificationFailed(e)) {
setErrorState('Verification failed, resubmit.')
}
else if (errorIndicatesMfaMaxAttempts(e)) {
setErrorState('Max attempts reached, re-initialize MFA.')
}
else if (errorIndicatesMfaTimeout(e)) {
setErrorState('Timeout reached, re-initialize MFA.')
}
}}
>
{errorState ?? 'Verify SMS MFA Code'}
</button>

useMfaEnrollment

useMfaEnrollment(): Object

Use this hook to enroll a user in MFA

Returns

Object

initEnrollmentWithSms - starts the MFA enrollment flow for SMS

initEnrollmentWithTotp - starts the MFA enrollment flow for TOTP

submitEnrollmentWithSms - completes the MFA enrollment flow for SMS

submitEnrollmentWithTotp - completes the MFA enrollment flow for TOTP

unenrollWithSms - unenrolls the SMS MFA method

unenrollWithTotp - unenrolls the TOTP MFA method

NameType
initEnrollmentWithSms(meta: { phoneNumber: string }) => Promise<void>
initEnrollmentWithTotp() => Promise<{ authUrl: string ; secret: string }>
submitEnrollmentWithSms(meta: { mfaCode: string ; phoneNumber: string }) => Promise<void>
submitEnrollmentWithTotp(meta: { mfaCode: string }) => Promise<void>
unenrollWithSms() => Promise<void>
unenrollWithTotp() => Promise<void>

Example

const {initEnrollment} = useMfaEnrollment();

<button
onClick={() => {
initEnrollment(
'sms',
{ phoneNumber: '<user-phone-number>' },
);
}}
>
Enroll in SMS MFA
</button>

Example

const {submitEnrollment} = useMfaEnrollment();

<button
onClick={() => {
submitEnrollment(
'sms',
{ phoneNumber: '<user-phone-number>', mfaCode: '<user-mfa-code>' },
);
}}
>
Enroll in SMS MFA
</button>

usePrivy

usePrivy(): PrivyInterface

React Hook that allows you to manage the user's current authentication state and access their linked accounts.

You should use this hook to access the Privy SDK from within your React components and custom hooks.

Returns

PrivyInterface


useRegisterMfaListener

useRegisterMfaListener(callbacks): void

Use this hook to register your app's logic for prompting users to complete MFA. When a user is required to complete MFA in order to use their embedded wallet, Privy will invoke the logic you register here to have the user complete MFA. This hook should be mounted somewhere towards the root of your application tree so that it can handle MFA required events from the entire application.

Parameters

NameTypeDescription
callbacksObjectPrivyEvents callbacks to register your logic for prompting users to complete MFA.
callbacks.onError?CallbackErrorCallback that will execute in the case of a non-successful MFA flow. Param {PrivyErrorCode} - the corresponding error code
callbacks.onMfaRequired(mfaMethods: ("sms" | "totp")[]) => voidCallback that will execute when MFA is required to complete a given action.

Returns

void

Example

const [mfaMethods, setMfaMethods] = useState([])
const [isMfaDialogOpen, setIsMfaDialogOpen] = useState(false)

// Prompt user to select from their enabled MFA methods
useRegisterMfaListener({
onMfaRequired: async (methods) => {
setMfaMethods(methods)
setIsMfaDialogOpen(true);
},
});

// Within MFA modal allow the user to select an MFA method
<MFAModal
mfaMethods={mfaMethods}
isOpen={isMfaDialogOpen}
setIsOpen={setIsMfaDialogOpen}
/>

See `useMfa` for how to execute the MFA flow within Privy in your App.

useWallets

useWallets(): UseWalletsInterface

Returns

UseWalletsInterface