Next.js 13中调用Next-auth的signIn()跳转/api/auth/error报404
问题:Next.js 13 + Next-auth 4.2 Google登录触发/api/auth/error 404错误
在Next.js 13应用中使用Next-auth 4.2实现Google登录,调用官方文档的signIn()函数时,被重定向至http://localhost:3000/api/auth/error页面并显示404错误。技术栈:React、Next.js 13、TypeScript 4.9、Next-auth 4.2,使用Prisma连接Railway数据库。
相关组件代码
登录按钮组件(login.jsx)
'use client' import { signIn } from 'next-auth/react' import "./nav-styles.css" export default function () { return ( <li className="list-none"> <button onClick={() => signIn()}>Sign in</button> </li> ) }
导航组件(nav.jsx)
import Login from "./login" import "./nav-styles.css" export default async function nav() { return ( <nav> <a href={'/'}> <h1><span className="logo-1">Addictive</span> Social</h1> </a> <ul> <Login /> </ul> </nav> ); }
Root Layout(layout.jsx)
import "./globals.css"; import Nav from "./auth/nav"; export const metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children }) { return ( <html lang="en"> <body className="bg-gray-20"> <Nav /> {children} </body> </html> ); }
排查与解决方案
- 确认Next-auth API路由存在:在Next.js 13 App Router模式下,必须创建
app/api/auth/[...nextauth]/route.js文件,用于配置Next-auth的核心逻辑。如果缺少该文件,会直接导致/api/auth路由不存在,触发404错误。 - 检查环境变量配置:确保
.env.local文件中正确配置以下变量:GOOGLE_CLIENT_ID:从Google Cloud控制台获取的OAuth客户端IDGOOGLE_CLIENT_SECRET:对应Google OAuth客户端密钥NEXTAUTH_SECRET:用于加密会话的密钥(可通过openssl rand -hex 32生成)NEXTAUTH_URL=http://localhost:3000:开发环境下的应用地址
- 验证Provider与适配器配置:在
[...nextauth]/route.js中需正确配置Google Provider和Prisma适配器,示例配置如下:
import NextAuth from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import prisma from "@/lib/prisma"; // 确保正确导入Prisma客户端实例 export const authOptions = { adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], secret: process.env.NEXTAUTH_SECRET, }; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };
- 修复导航组件的异步声明:导航组件
nav无需声明为async function(除非有数据获取需求),改成普通函数可避免客户端组件渲染顺序问题:
import Login from "./login" import "./nav-styles.css" export default function nav() { // 移除async return ( <nav> <a href={'/'}> <h1><span className="logo-1">Addictive</span> Social</h1> </a> <ul> <Login /> </ul> </nav> ); }
- 重启开发服务器:修改环境变量或路由配置后,需重启Next.js开发服务器,确保新配置生效。
内容的提问来源于stack exchange,提问作者Ethan
相关产品推荐
相关产品推荐

