Email OTP in Better Auth, end to end
Set up the Better Auth email OTP plugin, choose a sender for the codes, and handle expiry, tries and rate limits in production.
Better Auth’s email OTP plugin handles the hard parts of a 6-digit email code: generating it, storing it, expiring it and checking it. It leaves one thing to you, which is sending the email. This post sets the plugin up and covers the choices that matter in production.
Server setup
// auth.ts
import { betterAuth } from "better-auth";
import { emailOTP } from "better-auth/plugins";
export const auth = betterAuth({
// your database adapter, as usual
plugins: [
emailOTP({
otpLength: 6,
expiresIn: 600, // seconds; the default is 300
allowedAttempts: 5, // the default is 3; "maxAttempts" is ignored
storeOTP: "hashed", // the default is "plain": the code itself in your database
async sendVerificationOTP({ email, otp, type }) {
// type: "sign-in" | "email-verification" | "forget-password" | "change-email"
await sendEmail({
to: email,
subject: `Your sign-in code is ${otp}`,
text: `Enter ${otp} to continue. It expires in 10 minutes.`,
});
},
}),
],
});
Client setup
import { createAuthClient } from "better-auth/client";
import { emailOTPClient } from "better-auth/client/plugins";
export const authClient = createAuthClient({ plugins: [emailOTPClient()] });
// 1. send the code
await authClient.emailOtp.sendVerificationOtp({ email, type: "sign-in" });
// 2. sign in with the code the user typed
await authClient.signIn.emailOtp({ email, otp });
Choosing what sends the email
sendEmail above is yours. Three things decide whether codes arrive:
- A verified sending domain. Send from
noreply@yourapp.inwith SPF, DKIM and DMARC set up. Codes from a Gmail address or an unverified domain land in spam. - A transactional provider, not a mailbox. Amazon SES, ZeptoMail, Resend or Postmark. Zoho Mail or Gmail SMTP have hourly limits and policies against bulk sending.
- Plain, short emails. The code in the subject line, no images, no marketing. Inbox providers treat code emails with links and images with more suspicion.
Production checklist
- Rate limit the send endpoint per email and per IP, and put a check such as Cloudflare Turnstile on the form. Otherwise anyone can use your app to email strangers.
- A resend wait of 30 seconds or so in your UI.
- Expiry and tries: 10 minutes and 5 tries are common; Better Auth’s defaults are 300 seconds and 3 tries. Set tries with
allowedAttempts. - Store a hash, not the code. With the default
storeOTP: "plain"the verification table holds the code in clear text until it is used or expires;"hashed"stores a hash and compares in constant time. - Watch bounces and complaints. A spike of either gets your sending domain throttled.
What we saw: the defaults, and a misspelled option
On 24 November 2026 we installed Better Auth 1.7.28 with its memory adapter, set up the plugin twice, sent a code and typed wrong codes until it refused. The first setup used maxAttempts: 5, as this post had it until that day.
| Setup | What the verification table held | Wrong codes before “Too many attempts” |
|---|---|---|
otpLength: 6, expiresIn: 600, maxAttempts: 5 |
The code itself, then :0, the tries counter |
3. The fourth answered 403 Too many attempts, and the right code after it 400 Invalid OTP |
otpLength: 6, expiresIn: 600, allowedAttempts: 5, storeOTP: "hashed" |
A 43-character hash, then :0 |
5. The sixth answered 403 Too many attempts |
maxAttempts raised no error and no warning; Better Auth reads opts.allowedAttempts || 3. The expiry was right in both: the row expired 600 seconds after the send. In the plugin’s source, "plain" is the default for storeOTP, and "encrypted" or your own hash function are the other choices.
Or let an API send and check the code
If you would rather not store codes or run email at all, SignOps Email OTP makes the code, sends it from your domain and checks it. With Better Auth, put it in a small plugin of your own: SignOps answers whether the code is right, and Better Auth makes the user and the session as usual.
// signops-otp.ts: a Better Auth plugin that sends and checks codes through SignOps
import { createAuthEndpoint, APIError } from "better-auth/api";
import { setSessionCookie } from "better-auth/cookies";
import { SignOps, SignOpsError } from "@signops/node";
const signops = new SignOps(process.env.SIGNOPS_KEY);
// SignOps answers 409, 410, 422 and 429 as errors; give Better Auth the same status, not a 500.
async function ask<T>(fn: () => Promise<T>) {
try { return await fn(); }
catch (e) {
if (!(e instanceof SignOpsError)) throw e;
const status = { 409: "CONFLICT", 410: "GONE", 429: "TOO_MANY_REQUESTS" }[e.status] ?? "BAD_REQUEST";
throw new APIError(status as "BAD_REQUEST", { message: e.message, code: e.code });
}
}
export const signopsOTP = () => ({
id: "signops-otp",
endpoints: {
signopsSend: createAuthEndpoint("/signops-otp/send", { method: "POST" }, async (ctx) => {
const r = await ask(() => signops.otp.send({ email: ctx.body.email, app_name: "Your App" }));
return ctx.json({ otp_id: r.otp_id });
}),
signopsVerify: createAuthEndpoint("/signops-otp/verify", { method: "POST" }, async (ctx) => {
const r = await ask(() => signops.otp.verify({ otp_id: ctx.body.otp_id, code: ctx.body.code }));
if (!r.valid) return ctx.json({ valid: false, tries_left: r.tries_left });
const found = await ctx.context.internalAdapter.findUserByEmail(r.email);
const user = found?.user ?? (await ctx.context.internalAdapter.createUser({
email: r.email, name: r.email.split("@")[0], emailVerified: true,
}));
const session = await ctx.context.internalAdapter.createSession(user.id);
await setSessionCookie(ctx, { session, user });
return ctx.json({ valid: true });
}),
},
});
Add signopsOTP() to plugins next to your other ones. Keep the otp_id in a cookie or your session rather than trusting one from the page if you prefer; the code itself is what proves the address.
What we saw: the plugin, with a real code
The same day we ran this plugin against the live API with our test app’s test key, sending to our own inbox.
| We did | What came back |
|---|---|
POST /api/auth/signops-otp/send |
200 in 3.8 seconds with an otp_id. The code was in Gmail as “180052 is your SignOps test code”. |
| Verify with a wrong code | 200 in 0.74 seconds, {"valid":false,"tries_left":4} |
| Verify with the right code | 200 in 0.64 seconds, {"valid":true}, and a better-auth.session_token cookie |
auth.api.getSession with that cookie |
The session, with one user created and emailVerified: true |
| The same code again, first version of the plugin | 500: the SignOps library throws on 409 already_done, and Better Auth turns an uncaught throw into a server error |
The same code again, with ask() above |
409, {"code":"already_done","message":"... Each code works once."} |
Without Better Auth, the same flow is two Route Handlers: see Next.js email OTP.
Sources: Better Auth: email OTP plugin, Better Auth: creating plugins, the better-auth 1.7.28 package source (dist/plugins/email-otp).