You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS13中NextAuthJS Discord登录开发正常,生产构建报错求助

解决NextAuth.js在Vercel生产构建时的路由类型错误

问题原因

Next.js 13 App Router的API路由文件(route.ts)只允许导出HTTP方法对应的处理函数(比如GET、POST),你当前代码里直接导出了authOptions变量,生产构建时的类型检查会严格校验这一点,因此抛出错误。开发环境的类型检查相对宽松,所以没触发这个问题。

修复方案

方案1:移除authOptions的导出(仅当前路由使用时)

修改app/api/auth/[...nextauth]/route.ts代码,将export const authOptions改为局部变量:

import NextAuth from "next-auth";
import type { NextAuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";

// 移除export,改为仅局部变量
const authOptions: NextAuthOptions = {
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID!,
      clientSecret: process.env.DISCORD_CLIENT_SECRET!,
    })
  ]
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }

方案2:抽离authOptions到单独文件(需要复用时)

如果项目中其他组件/路由需要用到authOptions,可以把它移到单独文件中,比如lib/auth.ts:

lib/auth.ts

import type { NextAuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";

export const authOptions: NextAuthOptions = {
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID!,
      clientSecret: process.env.DISCORD_CLIENT_SECRET!,
    })
  ]
};

然后在路由文件中导入使用:

app/api/auth/[...nextauth]/route.ts

import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }

这样既满足复用需求,又不会在路由文件中导出非HTTP方法字段,能通过生产构建的类型检查。

内容的提问来源于stack exchange,提问作者user21981180

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:13:14