使用Better Auth发送验证邮件时sendVerification未触发问题
Better Auth中验证邮件发送函数未触发问题
问题描述
使用Better Auth实现身份认证,已配置requireEmailVerification: true,但sendVerificationEmail函数始终未被调用。手动测试Brevo邮件服务正常,但Postman调用注册接口时,仅能收到接口响应,验证邮件完全没发送。
相关代码
Better Auth配置代码
import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { nextCookies } from "better-auth/next-js"; import { prisma } from "./prisma"; import { sendVerificationEmail } from "./sendVerificationEmail"; export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "postgresql", }), plugins: [nextCookies()], emailAndPassword: { enabled: true, requireEmailVerification: true, }, emailVerification: { sendVerificationEmail: async ({ user, url, }) => { await sendVerificationEmail( user.email, user.name || "Volunteer", url ); }, }, });
邮件发送函数代码
import { brevo } from "./brevo"; export async function sendVerificationEmail( email: string, userName: string, verificationUrl: string ) { console.log("EMAIL FUNCTION CALLED"); try { console.log("Before Brevo") const response = await brevo.transactionalEmails.sendTransacEmail({ sender: { email: "special23@gmail.com", name: "Volunteer Verification", }, to: [ { email, name: userName, }, ], subject: "Verify your volunteer account", htmlContent: ` <html> <body> <h2> Welcome ${userName} </h2> <p> Thank you for registering as a volunteer. </p> <p> Click below to verify your email: </p> <a href="${verificationUrl}"> Verify Email </a> </body> </html> `, }); console.log("BREVO RESPONSE:", response); } catch (error) { console.log("BREVO ERROR:", error); throw new Error( "Failed to send verification email" ); } }
排查建议
核对Better Auth版本与配置结构
部分版本的Better Auth会要求将sendVerificationEmail钩子嵌套在emailAndPassword配置内,而非顶层的emailVerification。尝试调整配置结构:emailAndPassword: { enabled: true, requireEmailVerification: true, sendVerificationEmail: async ({ user, url }) => { await sendVerificationEmail(user.email, user.name || "Volunteer", url); } }检查用户验证状态
查看数据库中用户表的emailVerified字段,如果该字段已存在值(非null/false),Better Auth会跳过验证邮件发送逻辑。确保新注册用户的该字段初始状态为未验证。添加钩子内部日志调试
在Better Auth的sendVerificationEmail钩子内添加日志,确认是否进入该逻辑:emailVerification: { sendVerificationEmail: async ({ user, url }) => { console.log("Better Auth钩子触发,用户邮箱:", user.email); // 新增日志 await sendVerificationEmail(user.email, user.name || "Volunteer", url); }, },启动项目后查看控制台输出,确认钩子是否被执行。
排查插件与上下文问题
检查nextCookies()插件是否正确配置,是否存在请求上下文传递异常,导致钩子无法正常执行异步操作。可暂时移除插件测试,看邮件是否能正常发送。
内容的提问来源于stack exchange,提问作者Himanshu Gour
相关产品推荐
相关产品推荐

