Next.js集成Next-Auth生产环境登录时出现504超时错误
问题:Next.js + Next-Auth生产环境登录504超时错误
我开发了一个基于Next.js并集成Next-Auth认证的应用,本地通过.env.local配置环境变量后运行正常,但部署到生产服务器并更新对应环境变量后,登录时出现504超时错误。
环境配置
开发环境
.env.local内容:
API_URL=https://api.mydomain.com/api NEXT_PUBLIC_API_URL=https://api.my_domain.com/api API_TOKEN="my-api-token" NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_SECRET="next-auth-secret"
生产环境
.env.local内容:
API_URL=https://api.mydomain.com/api NEXT_PUBLIC_API_URL=https://api.my_domain.com/api API_TOKEN="my-api-token" NEXTAUTH_URL=https://my_domain.com NEXTAUTH_SECRET="next-auth-secret"
Next-Auth配置文件(src/app/api/auth/[...nextauth]/route.js)
开发与生产环境该文件完全一致:
import axios from "axios"; import NextAuth from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; const handler = NextAuth({ secret: process.env.NEXTAUTH_SECRET, providers: [ CredentialsProvider({ name: "Credentials", credentials: { email: { label: "Email", type: "email", placeholder: "example@mail.com", }, password: { label: "Password", type: "password", }, }, async authorize(credentials, req) { try { // Check if the credentials were provided if (!credentials.email || !credentials.password) { return null; } // Check if the user has an account const data = await axios(process.env.API_URL + `/auth/local`, { method: "POST", headers: { "Content-Type": "application/json", }, data: { identifier: credentials.email, password: credentials.password, }, }); // Extract jwt and user data const jwt = data?.data?.jwt; const user = { ...data?.data?.user, jwt, }; // If user doesnt have an account redirect him back to login if (jwt) { return user; } return null; } catch (error) { console.log(error?.message); return null; } }, }), ], callbacks: { // JWT callback is called as first async jwt({ token, user, session }) { // Only on Sign In (The user object is not null only on first Sign In) // add id, confirmed, blocked and jwt from the user to the token object if (user) { return { ...token, id: user.id, confirmed: user.confirmed, blocked: user.blocked, jwt: user.jwt, }; } return token; }, // Store the access token into the session for Client side async session({ session, token, user }) { // Pass the id, confirmed, blocked and jwt from the token to the session object return { ...session, user: { ...session.user, id: token.id, confirmed: token.confirmed, blocked: token.blocked, jwt: token.jwt, }, }; }, }, }); export { handler as GET, handler as POST };
症状
生产环境提交登录凭据后,应用向https://my_domain.com/api/auth/callback/credentials发送POST请求,始终返回504超时错误,认证流程无法完成。已确认:
- 服务器网络连通正常
- 环境变量配置正确
- API可通过HTTPS正常访问
- 开发环境连接生产API时运行正常
可能的原因及解决建议
1. 生产服务器无法访问后端API(网络策略限制)
虽然本地能访问生产API,但生产服务器可能受防火墙、安全组或内网策略限制,无法向外请求https://api.mydomain.com/api。
- 解决:在生产服务器上执行curl命令测试API连通性:
如果请求超时或失败,联系服务器管理员开放对应端口的出站权限,或检查API是否允许生产服务器IP访问。curl -X POST https://api.mydomain.com/api/auth/local -H "Content-Type: application/json" -d '{"identifier":"test@example.com","password":"test123"}'
2. axios请求未设置超时时间,触发网关超时
当前axios请求未配置超时,若后端API响应缓慢,会导致Next.js路由处理超时,触发504错误。
- 解决:在axios请求中添加超时配置(例如10秒):
const data = await axios(process.env.API_URL + `/auth/local`, { method: "POST", headers: { "Content-Type": "application/json", }, data: { identifier: credentials.email, password: credentials.password, }, timeout: 10000, // 10秒超时 });
3. Next-Auth会话存储配置问题(生产环境默认内存存储)
Next.js生产环境中,默认的内存会话存储在多实例部署或服务器重启时会失效,也可能因内存限制导致处理延迟。
- 解决:配置持久化会话存储,例如使用Redis:
安装对应依赖:
在NextAuth配置中添加适配器:npm install next-auth @next-auth/redis-adapter ioredisimport Redis from "ioredis"; import RedisAdapter from "@next-auth/redis-adapter"; const redis = new Redis(process.env.REDIS_URL); const handler = NextAuth({ secret: process.env.NEXTAUTH_SECRET, adapter: RedisAdapter(redis), // 其他原有配置... });
4. 反向代理未传递正确请求头
生产服务器若使用Nginx等反向代理,未传递Host或X-Forwarded-Proto头会导致Next-Auth无法正确识别请求来源,引发处理延迟。
- 解决:调整反向代理配置,以Nginx为例:
同时在location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }next.config.js启用信任代理:module.exports = { trustProxy: true, // 其他配置... }
5. 环境变量未正确加载
即使本地修改了.env.local,生产服务器可能未正确读取该文件,或部署平台(如Vercel)需通过控制台设置环境变量而非上传文件。
- 解决:
- 在生产服务器执行
echo $NEXTAUTH_URL确认变量值正确。 - 若使用部署平台,直接在平台控制台添加所有环境变量,不依赖本地
.env.local文件。
- 在生产服务器执行
6. SSL证书验证问题
生产服务器或API的SSL证书无效、过期,或证书链不完整,会导致axios请求因SSL验证失败而挂起。
- 解决:
- 访问
https://api.mydomain.com/api确认证书无浏览器警告。 - 排查阶段可临时跳过SSL验证(生产环境禁用):
确认问题后需立即修复证书。import https from 'https'; const data = await axios(process.env.API_URL + `/auth/local`, { method: "POST", headers: { "Content-Type": "application/json", }, data: { identifier: credentials.email, password: credentials.password, }, httpsAgent: new https.Agent({ rejectUnauthorized: false }), });
- 访问
内容的提问来源于stack exchange,提问作者Samuel
相关产品推荐
相关产品推荐

