Sign-in codes with Better Auth
Send Better Auth's one-time codes, magic links, verification emails and password resets through Charchy Send, with expiring codes, idempotency keys and sending after the response.
Better Auth calls a function you give it with the code or link. Make that function call Charchy Send. Written for Better Auth 1.7 with Next.js; on Convex, schedule the send instead.
npm install @charchy/send1. The client
import "server-only"
import { CharchySend } from "@charchy/send"
/** Reads CHARCHY_SEND_KEY when an email is sent, not now: `next build` never needs the key. */
export const send = new CharchySend()
export const FROM = process.env.CHARCHY_SEND_FROM! // "My App <no-reply@myapp.com>"2. Codes, links, verification and resets
import { type SendEmailParams } from "@charchy/send"
import { betterAuth } from "better-auth"
import { emailOTP, magicLink } from "better-auth/plugins"
import { after } from "next/server"
import { FROM, send } from "@/lib/charchy-send"
const CODE_LIFETIME_SECONDS = 5 * 60
/** Better Auth logs an error thrown here; it never reaches the person signing in. */
async function sendAuthEmail(email: Omit<SendEmailParams, "from">, idempotencyKey: string) {
const { error } = await send.emails.send({ from: FROM, ...email }, { idempotencyKey })
if (error) throw error
}
export const auth = betterAuth({
// …your database and other options
advanced: {
// Send after the response, so a request's timing never shows whether an account exists.
// On Vercel without Next.js, or on Cloudflare Workers: their waitUntil.
backgroundTasks: { handler: (promise) => after(promise) },
},
emailAndPassword: {
enabled: true,
async sendResetPassword({ user, url, token }) {
await sendAuthEmail(
{
to: user.email,
subject: "Reset your password",
text: `Reset your password: ${url}`,
html: `<p><a href="${url}">Reset your password</a>. The link works once.</p>`,
tags: { type: "password_reset" },
},
`password-reset/${token}`
)
},
},
emailVerification: {
async sendVerificationEmail({ user, url, token }) {
await sendAuthEmail(
{
to: user.email,
subject: "Confirm your email",
text: `Confirm your email: ${url}`,
html: `<p><a href="${url}">Confirm your email</a></p>`,
tags: { type: "email_verification" },
},
`verify-email/${token}`
)
},
},
plugins: [
emailOTP({
expiresIn: CODE_LIFETIME_SECONDS,
async sendVerificationOTP({ email, otp, type }) {
// type: "sign-in" | "email-verification" | "forget-password"
await sendAuthEmail(
{
to: email,
subject: `Your code: ${otp}`,
text: `Your code is ${otp}. It expires in 5 minutes.`,
html: `<p>Your code is <strong>${otp}</strong>. It expires in 5 minutes.</p>`,
// A code that can't leave in time is dropped and refunded.
expiresAt: new Date(Date.now() + CODE_LIFETIME_SECONDS * 1000),
tags: { type: `otp_${type.replaceAll("-", "_")}` },
},
// A new code is a new email; the same code retried is not.
`otp/${type}/${email}/${otp}`
)
},
}),
magicLink({
expiresIn: CODE_LIFETIME_SECONDS,
async sendMagicLink({ email, url, token }) {
await sendAuthEmail(
{
to: email,
subject: "Your sign-in link",
text: `Sign in: ${url}`,
html: `<p><a href="${url}">Sign in</a>. The link works once, for 5 minutes.</p>`,
expiresAt: new Date(Date.now() + CODE_LIFETIME_SECONDS * 1000),
tags: { type: "magic_link" },
},
`magic-link/${token}`
)
},
}),
],
})- Don't make the request wait on the email. Better Auth's docs advise
against awaiting the send: the time a request takes would show whether an
account exists.
advanced.backgroundTasks.handlerruns these callbacks after the response — here through Next.js'safter(); on Vercel or Cloudflare Workers without Next.js, pass theirwaitUntil. Without the option, Better Auth awaits the callback. - Errors are logged, not shown. Better Auth catches an error thrown in
these callbacks and logs it, and the person sees the usual "check your
email". Watch your logs for
error.code(insufficient_balance,domain_not_verified, …). The SDK has already retried network errors,5xxand429. expiresAtmatches the code's lifetime (expiresIn, 300 seconds by default): a code that couldn't leave in time is dropped and refunded instead of arriving dead.- Idempotency keys come from the code or token, so a retry never sends a second email, and a new code always does.
- The code in the subject shows in the notification, and stops Gmail from threading two codes into one conversation.
3. Try it
With a test key in CHARCHY_SEND_KEY, sign in as
delivered@sim.charchy.krd: the email shows on the dashboard's Emails
page as delivered, with your tags. Sign in as bounced@sim.charchy.krd to see
what happens to an address that doesn't exist — the bounce reaches your
webhook as email.bounced.