To authenticate your users with a one-time passcode (OTP) sent to their email address, use the useLoginWithEmail hook.To authenticate your users with Privy’s out of the box UIs, check out UI components here. Send Code
sendCode: ({email: string, disableSignup?: boolean}) => Promise<void>
Parameters
The email address of the user to log in.
Whether to disable the ability to sign up with the email address.
Returns
A promise that resolves when the code is sent.
Login with Code
loginWithCode: ({ code: string }) => Promise<void>;
Parameters
The one-time passcode sent to the user’s email address.
Returns
A promise that resolves when the user is logged in.
Usage
import { useState } from "react";
import { useLoginWithEmail } from "@privy-io/react-auth";
export default function LoginWithEmail() {
const [email, setEmail] = useState("");
const [code, setCode] = useState("");
const { sendCode, loginWithCode } = useLoginWithEmail();
return (
<div>
<input onChange={(e) => setEmail(e.currentTarget.value)} value={email} />
<button onClick={() => sendCode({ email })}>Send Code</button>
<input onChange={(e) => setCode(e.currentTarget.value)} value={code} />
<button onClick={() => loginWithCode({ code })}>Login</button>
</div>
);
}
Tracking Flow State
Track the state of the OTP flow via the state variable returned by the
useLoginWithEmail hook.type OtpFlowState =
| {status: 'initial'}
| {status: 'error'; error: Error | null}
| {status: 'sending-code'}
| {status: 'awaiting-code-input'}
| {status: 'submitting-code'}
| {status: 'done'};
status
'initial' | 'error' | 'sending-code' | 'awaiting-code-input' | 'submitting-code' | 'done'
The current state of the OTP flow.
The error that occurred during the OTP flow.
Callbacks
You can optionally pass callbacks into the useLoginWithEmail hook to run custom logic after a successful login or to handle errors that occur during the flow.onComplete
onComplete?: ((params: {
user: User;
isNewUser: boolean;
wasAlreadyAuthenticated: boolean;
loginMethod: LoginMethod | null;
loginAccount: LinkedAccountWithMetadata | null;
}) => void) | undefined
Parameters
The user object corresponding to the authenticated user.
Whether the user is a new user or an existing user.
Whether the user entered the application already authenticated.
The method used by the user to login.
loginAccount
LinkedAccountWithMetadata | null
The account corresponding to the loginMethod used.
onError
onError: (error: Error) => void
Parameters
The error that occurred during the login flow.
Resources
To authenticate your users with a one-time passcode (OTP) sent to their email address, use the useLoginWithEmail hook.To authenticate your users with Privy’s out of the box UIs, check out UI components here. Send Code
sendCode: ({email: string}) => Promise<{success: boolean}>
Parameters
The email address of the user to log in.
Returns
A promise that resolves to an object with a success property indicating if the code was sent successfully.
Login with Code
loginWithCode: ({ code: string, email?: string, disableSignup?: boolean }) => Promise<{user: PrivyUser; isNewUser: boolean}>
Parameters
The one-time passcode sent to the user’s email address.
The user’s email address. Though this parameter is optional, it is highly recommended that you pass the user’s email address explicitly.
Whether to disable the ability to sign up with the email address.
Returns
The user object returned by the login process.
Usage
import { useState } from 'react';
import { useLoginWithEmail } from '@privy-io/expo';
export default function LoginWithEmail() {
const [email, setEmail] = useState('');
const [code, setCode] = useState('');
const { sendCode, loginWithCode } = useLoginWithEmail();
return (
<View>
<TextInput value={email} onChangeText={setEmail} placeholder="Email" />
<Button onPress={() => sendCode({ email })}>Send Code</Button>
<TextInput value={code} onChangeText={setCode} placeholder="Code" />
<Button onPress={() => loginWithCode({ code, email })}>Login</Button>
</View>
);
}
Tracking login flow state
The state variable returned from useLoginWithEmail will always be one of the following values.type OtpFlowState =
| {status: 'initial'}
| {status: 'error'; error: Error | null}
| {status: 'sending-code'}
| {status: 'awaiting-code-input'}
| {status: 'submitting-code'}
| {status: 'done'};
status
'initial' | 'error' | 'sending-code' | 'awaiting-code-input' | 'submitting-code' | 'done'
The current state of the email login flow.
The error that occurred during the email login flow.
Callbacks
You can optionally pass callbacks into the useLoginWithEmail hook to run custom logic after an OTP has been sent, after a successful login, or to handle errors that occur during the flow.onSendCodeSuccess
onSendCodeSuccess?: ((email: string) => void) | undefined
Parameters
The email the code was sent to.
onLoginSuccess
onLoginSuccess?: ((user: User, isNewUser: boolean) => void) | undefined
Parameters
The PrivyUser returned by loginWithCode.
Whether the user is a new user or an existing user.
onError
onError?: (error: Error) => void
Parameters
The error that occurred during the login flow.
Resources
To authenticate a user via their email address, use the Privy client’s email handler.Send Code
sendCode(to email: String) async throws
Parameters
The email address of the user to log in.
Returns
Nothing, indicating success.
Throws
An error if sending the code fails.Login with Code
loginWithCode(_ code: String, sentTo email: String) async throws -> PrivyUser
Parameters
The one-time passcode sent to the user’s email address.
The user’s email address.
Returns
The authenticated Privy user
Throws
An error if logging the user in is unsuccessful.Usage
// Send code to user's email
do {
try await privy.email.sendCode(to: "[email protected]")
// successfully sent code to users email
} catch {
print("error sending code to \(email): \(error)")
}
// Log the user in
do {
let user = try await privy.email.loginWithCode("123456", sentTo: "[email protected]")
// user successfully logged in
} catch {
print("error logging user in: \(error)")
}
To authenticate a user via their email address, use the Privy client’s email handler.Send Code
sendCode(email: String): Result<Unit>
Parameters
The email address of the user to log in.
Returns
A Result object that indicates whether the operation was successful. Returns Result.success if the code was sent successfully, or Result.failure if there was an error.
Login with Code
loginWithCode(code: String, email: String?): Result<PrivyUser>
Parameters
The one-time passcode sent to the user’s email address.
(Optional) The user’s email address. Though this parameter is optional, it is highly recommended that you pass the user’s email address explicitly. If email is omitted, the email from sendCode will be used.
Returns
A Result object containing the PrivyUser if successful, or an error if the operation failed.
Usage
// Send code to user's email
val result: Result<Unit> = privy.email.sendCode(email = "[email protected]")
result.fold(
onSuccess = {
// OTP was successfully sent
},
onFailure = {
println("Error sending OTP: ${it.message}")
}
)
// Authenticate with the OTP code
val result: Result<PrivyUser> = privy.email.loginWithCode(code = "123456", email = "[email protected]")
result.fold(
onSuccess = { user ->
// User logged in
},
onFailure = {
println("Error logging in user: ${it.message}")
}
)
To authenticate a user via their email address, use the Privy client’s Email handler.Send Code
SendCode(string email): Task<bool>
Parameters
The email address of the user to log in.
Returns
A Task that resolves to a boolean indicating whether the code was sent successfully.
Login with Code
LoginWithCode(string email, string code): Task
Parameters
The user’s email address.
The one-time passcode sent to the user’s email address.
Returns
A Task that completes when the user is successfully authenticated, or throws an exception if authentication fails.
Usage
// Send code to user's email
bool success = await PrivyManager.Instance.Email.SendCode(email);
if (success)
{
// Prompt user to enter the OTP they received at their email address through your UI
}
else
{
// There was an error sending an OTP to your user's email
}
// Authenticate with the OTP code
try
{
// User will be authenticated if this call is successful
await PrivyManager.Instance.Email.LoginWithCode(email, code);
// User is now logged in
}
catch
{
// If "LoginWithCode" throws an exception, user login was unsuccessful.
Debug.Log("Error logging user in.");
}
To authenticate a user via their email address, use the Privy client’s email handler.Send Code
sendCode(String email): Future<Result<void>>
Parameters
The email address of the user to log in.
Returns
A Result object that indicates whether the operation was successful. Returns Result.success if the code was sent successfully, or Result.failure if there was an error.
Login with Code
loginWithCode({required String code, String? email}): Future<Result<PrivyUser>>
Parameters
The one-time passcode sent to the user’s email address.
(Optional) The user’s email address. Though this parameter is optional, it is highly recommended that you pass the user’s email address explicitly. If email is omitted, the email from sendCode will be used.
Returns
Result<PrivyUser>
Future<Result<PrivyUser>>
A Result object containing the PrivyUser if successful, or an error if the operation failed.
Usage
// Send code to user's email
final Result<void> result = await privy.email.sendCode(email);
result.fold(
onSuccess: (_) {
// OTP was sent successfully
},
onFailure: (error) {
// Handle error sending OTP
print(error.message);
},
);
// Authenticate with the OTP code
final Result<PrivyUser> result = await privy.email.loginWithCode(
code: code,
email: email,
);
result.fold(
onSuccess: (user) {
// User authenticated successfully
},
onFailure: (error) {
// Handle authentication error
},
);
Resources