Next.js 13 App目录+src下配置Next Auth GoogleProvider遇404错误求助
问题重现
使用Next.js 13实验性App Router(带src目录)配置NextAuth Google OAuth认证,点击登录按钮后重定向到http://localhost:3000/api/auth/error并出现404错误,已尝试硬编码OAuth凭证仍无法解决。
核心错误点
你的配置存在两个关键问题,均因混淆App Router与Pages Router的NextAuth配置规则导致:
API路由文件结构错误
App Router的API路由要求在对应路径下创建route.ts文件,而非直接命名为[...nextauth].ts。你当前的文件路径src/app/api/auth/[...nextauth].ts不符合App Router的路由规则,导致Next.js无法识别该认证路由。API路由导出方式错误
App Router的API路由需要显式导出GET和POST函数,而非默认导出NextAuth实例,这与Pages Router的写法完全不同。
正确配置步骤
1. 修正API路由文件结构
将原src/app/api/auth/[...nextauth].ts文件移动到src/app/api/auth/[...nextauth]/route.ts——即先创建[...nextauth]文件夹,再在内部新建route.ts文件。
2. 修正API路由代码
修改src/app/api/auth/[...nextauth]/route.ts内容如下:
import NextAuth from 'next-auth' import GoogleProvider from 'next-auth/providers/google' const handler = NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID as string, clientSecret: process.env.GOOGLE_CLIENT_SECRET as string, }) ], }) // App Router下必须显式导出GET和POST方法 export { handler as GET, handler as POST }
3. 验证Google OAuth回调URL
确保Google Cloud控制台中OAuth凭证的授权回调URL设置为:http://localhost:3000/api/auth/callback/google
4. 其他检查项
- 确认
signIn函数已从next-auth/react正确导入:import { signIn } from 'next-auth/react' - 你的
ProvidersWrapper组件写法正确,保持不变,确保layout.tsx中已用它包裹所有子组件。 - 环境变量需存储在项目根目录的
.env.local文件中,格式如下:GOOGLE_CLIENT_ID=你的客户端ID GOOGLE_CLIENT_SECRET=你的客户端密钥
测试验证
重启Next.js开发服务器,点击登录按钮,此时应该会正常跳转到Google授权页面,授权完成后返回应用,不再出现404错误。
内容的提问来源于stack exchange,提问作者Maramal

