The plugin supports One-Time Passwords (OTP) delivered via Email or SMS.
Configuration
In the server config, use otpOptions to define how codes are sent and validated:
sendOTP: An async function receiving { user, otp, ctx }. Use this to integrate your email/SMS provider.period: Validity in minutes (default: 3).digits: Number of digits (default: 6).allowedAttempts: Max verification attempts (default: 5).storeOTP: Storage strategy ("plain", "encrypted", or "hashed"). You can also provide a custom object with encrypt and decrypt functions.
Usage
- Send:
authClient.twoFactor.sendOtp() - Verify:
authClient.twoFactor.verifyOtp({ code, trustDevice: true })
// Server Configuration Example
export const auth = betterAuth({
plugins: [
twoFactor({
otpOptions: {
sendOTP: async ({ user, otp }) => {
await sendEmail({
to: user.email,
subject: "Your verification code",
text: `Your code is: ${otp}`,
});
},
period: 5,
digits: 6,
allowedAttempts: 5,
storeOTP: "encrypted",
},
}),
],
});
// Client Usage
const verifyOtp = async (code: string) => {
const { data, error } = await authClient.twoFactor.verifyOtp({
code,
trustDevice: true,
});
};