Skip to content

Login with email

To authenticate a user via their email address, use the Privy client's email handler. This is a two step process:

  1. Send an OTP to the user provided email address.
  2. Verify the OTP sent to the user.

TIP

With Privy, users can either login with their email or link their email to an existing account.

1. Send an OTP to the user's email address

To login a user by their email address or to have them link their email to an existing account, first send an OTP by calling the sendCode method.

swift
let otpSentSuccessfully: Bool = await privy.email.sendCode(to: "[email protected]")

if otpSentSuccessfully {
    // prompt user for OTP
} else {
    // handle unsuccessful attempt appropriately
    // OTP could fail if the network request fails
}

2. Authenticate with OTP

The user will then receive an email with a 6-digit OTP. Prompt for this OTP within your application, then pass the OTP to Privy's loginWithCode method to have the user login with their email address, or linkWithCode to have the user link their email address to their existing account.

As a parameter to loginWithCode/linkWithCode, pass an object with the following fields:

FieldTypeDescription
codeStringOTP code inputted by the user in your app.
sentToString?(Optional) The user's email address. Though this parameter is optional, it is highly recommended that you pass the user's email address explicitly.
swift
let authState = try await privy.email.loginWithCode("123456", sentTo: "[email protected]")

if case .authenticated(_) = authState {
    // user authenticated!
}

Tracking login flow state

You can add provide a listener to receive state updates during the login with email process.

swift
privy.email.setOtpFlowStateChangeCallback { otpFlowState in
    switch otpFlowState {

    case .initial:
        // Starting state
    case .sourceNotSpecified:
        // Email was not specified before calling "send code"
    case .sendCodeFailure(let error):
        // There was an error sending the code. Could be because of an
        // incorrectly formatted email or a network error
    case .sendingCode:
        // Sending code
    case .awaitingCodeInput:
        // The OTP was sent, now awaiting user input
    case .submittingCode:
        // Submitted code
    case .incorrectCode:
        // User typed in an incorrect code
    case .loginError(let error):
        // There was a network error while logging in.
    case .done:
        // OTP flow complete
    }
}