Skip to main content

Transactional auth email

Deliver reset, verification, one-time code, and invitation email through one typed hook.

Pass one email hook to createBetterConvexAuth. The library calls it for every auth email that an enabled capability sends. The application is responsible for recipients, templates, delivery, and retries. Better Convex does not install a sending provider or render email.

Add the email hook

convex/auth.ts
import { createBetterConvexAuth } from '@lupinum/better-convex-nuxt/better-auth/server'

import { components, internal } from './_generated/api'
import type { DataModel } from './_generated/dataModel'

export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
  emailAndPassword: {
    requireEmailVerification: true,
    passwordReset: true,
    revokeSessionsOnPasswordReset: true,
  },
  emailVerification: { sendOnSignUp: true },
  email: async (ctx, message) => {
    switch (message.type) {
      case 'verify-email':
      case 'reset-password':
        await ctx.runMutation(internal.authMail.submitLink, {
          kind: message.type,
          recipient: message.to,
          url: message.url,
        })
        return
      default:
        throw new Error(`Unsupported auth email: ${message.type}`)
    }
  },
})

internal.authMail.submitLink is an application-owned internal mutation in this example, not a library export. It must durably enqueue or schedule the approved message, with bounded retry and secret-retention rules. Do not expose a public endpoint that accepts arbitrary recipients or links.

Message types

message.to is always the recipient address. The other fields depend on message.type:

typeSent whenFields
verify-emailEmail verification is requestedurl, token, user
reset-passwordA password reset is requestedurl, token, user
email-otpThe emailOTP capability sends a codeotp, purpose
two-factor-otpThe twoFactor capability sends a one-time codeotp, user
organization-invitationThe organization capability invites a memberinvitationId, role, organization, inviter
delete-accountdeleteUser is enabled and a person deletesurl, token, user

purpose is sign-in, email-verification, or forget-password. A forget-password code is sent only when emailAndPassword.passwordReset is true, and an email-verification code only to an address that is not verified yet. Other requests still answer with success and send no mail, so the answer does not show whether an account exists. user and inviter contain id, email, and name. An invitation has no link. Build it from your application origin and invitationId, for example with requireAuthOrigin('SITE_URL').

The email option only gives Better Auth a way to send mail. Whether password sign-in waits for a verified address is set by emailAndPassword: requireEmailVerification is true unless you pass false. Link-based password reset is opt-in: set emailAndPassword.passwordReset: true to offer /request-password-reset and receive reset-password messages. With emailOTP, the code-based reset routes (/email-otp/request-password-reset and /email-otp/reset-password) are blocked unless passwordReset is true. Handle every type that your enabled capabilities can send.

Write the verify-email message so it says: "If you did not create an account, ignore this email." See Password sign-in and access by email.

Local development and the dev outbox

On a loopback SITE_URL (http://localhost:3000, http://127.0.0.1:3000) without siteOrigins, the dev outbox writes each code and link to the Convex function log, as [better-convex-nuxt dev outbox] email-otp to you@example.com: code 123456. Read it with pnpm exec better-convex-nuxt convex logs. NODE_ENV plays no part.

  • Without the email option, the log is the only delivery, so a new project can sign in before it has a mail provider.
  • With the email option, the library writes the log line first and then calls your hook. You can test your templates and queue locally and still read the code when the hook has no provider key.

On any other SITE_URL, the dev outbox never writes to the log, with or without the hook. A cloud development deployment whose SITE_URL is http://localhost:3000 counts as local: everyone who can read its logs can read the codes.

No email option on a deployment

On a SITE_URL that is not loopback, createBetterConvexAuth throws when the deployment must send mail (emailOTP, password verification or reset, organization invitations) and has no email option. The deploy fails and the previous version keeps running. Add the email option, or leave those features out.

Submit durable work

The hook receives a mutation or action context. The library fails with AUTH_EMAIL_REQUIRES_WRITABLE_CONTEXT before it calls the hook from a query. Use ctx.runMutation to submit durable work.

The library awaits the hook, but a rejected promise does not fail the Better Auth request. Better Auth runs every auth email as a background task and only logs a failure, so the user still sees success (this also keeps password reset from revealing which addresses have accounts). Treat the hook as a durable submission that must not fail: enqueue the work, then retry delivery from your own queue.

When the hook rejects, the library logs AUTH_EMAIL_DELIVERY_FAILED with the message type and a sanitized cause, and hands Better Auth only that static error. The raw error, which may echo a reset URL, token, or code, is never logged. Do not await a mail provider's network response or start an untracked promise. Auth token creation and a later submission can be separate transactions; test submission failure and safe user retries in the application. Never include the credential-bearing message in an error.

Until your queue sends the email, the code or link is stored in plain text. Store it in a row of your own table, schedule the sending action with only the row ID, and delete the row after the email is sent. Do not pass the code in the arguments of a scheduled function: they stay in the _scheduled_functions system table after the function runs, and people with access to the Convex dashboard can read them.

These rules limit what a stored code can do:

  • Better Auth stores the code hashed in the auth tables. This is the library default (storeOTP: 'hashed'); another emailOTP.storeOTP value changes it. With the default, only your queue holds the plain code.
  • The code expires after emailOTP.expiresIn seconds, 300 by default. After that, a stored code is worthless. Keep this value short.
  • The code stops working after emailOTP.allowedAttempts wrong codes, 3 by default.

A reset or verification link gives access in the same way until it expires.

Configure the capabilities

The library sets the email callbacks of Better Auth. These options are rejected: emailAndPassword.sendResetPassword, emailVerification.sendVerificationEmail, emailOTP.sendVerificationOTP, twoFactor.otpOptions.sendOTP, and organization.sendInvitationEmail. Enabling emailOTP without email is a configuration error.

emailAndPassword, emailVerification, and emailOTP take plain options objects. Password hashing, minimum length, automatic sign-in, and the other settings that the library sets remain protected.

Use environment-independent build options for schema generation. Every enabled plugin must match the generated local component schema.

Email codes need their own expiry, abuse limits, and delivery-latency tests. A durable queue does not automatically stop sending after a code expires. Never log codes, reset URLs, or queued message bodies in application diagnostics.