Next.js 13中Next Auth登录函数开发正常,Vercel生产环境失败
Next.js 13 + Next-Auth 生产环境登录失败(浏览器差异问题)
开发环境中邮箱密码登录功能正常,但部署到Vercel生产环境后出现以下浏览器差异的登录失败问题:
- Mac笔记本Chrome:报405错误,重定向至
/login# - Mac/iOS Safari:报304错误,重定向至Next-Auth标准错误页
/api/auth/error
已确认NEXTAUTH_URL配置正确,可通过以下方案排查修复:
1. 修正表单提交触发逻辑
当前按钮为type="submit",会触发表单默认提交行为,与signIn的请求方法冲突,导致405错误。
解决方法:
将按钮类型改为button,避免默认提交:
<button type="button" // 修改此处 disabled={!isFormValid()} className={`flex w-full justify-center rounded-md bg-amber-500 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:amber-indigo-600 ${isFormValid()? 'hover:bg-amber-700' : '' }`} onClick={() => signIn('credentials', {email, password, redirect: true, callbackUrl: '/dashboard'})} > Sign In </button>
或在onClick中阻止默认事件:
onClick={(e) => { e.preventDefault(); signIn('credentials', {email, password, redirect: true, callbackUrl: '/dashboard'}) }}
2. 验证Credentials提供者逻辑
确保[...nextauth].js/ts中的Credentials提供者authorize函数正确处理请求,无未捕获错误:
export const authOptions = { providers: [ CredentialsProvider({ name: 'Credentials', credentials: { email: { label: 'Email', type: 'email' }, password: { label: 'Password', type: 'password' } }, async authorize(credentials) { // 校验参数完整性 if (!credentials?.email || !credentials?.password) return null; // 数据库查询与密码验证逻辑 const user = await getUserByEmail(credentials.email); if (!user || !await verifyPassword(credentials.password, user.passwordHash)) { return null; } // 返回合法用户对象 return { id: user.id, email: user.email }; } }) ], // 其他配置... }
3. 确认Vercel环境变量生效
即使本地配置了NEXTAUTH_URL,仍需检查Vercel控制台的环境变量:
- 值为生产环境完整URL(如
https://your-domain.vercel.app) - 已重新部署应用,确保变量生效
4. 处理Safari缓存问题(304错误)
Safari对GET请求缓存策略严格,可在[...nextauth].js中添加缓存禁用响应头:
export const authOptions = { // ...其他配置 callbacks: { async redirect({ url, baseUrl }) { return url.startsWith(baseUrl) ? url : baseUrl; } }, headers: { 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' } }
5. 检查版本兼容性
确保Next.js 13与Next-Auth版本兼容(推荐使用Next-Auth v4.x),避免版本不匹配导致的路由或请求处理异常。
内容的提问来源于stack exchange,提问作者Bogdan Andrei
相关产品推荐
相关产品推荐

