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

Next.js最新版API路由报错:需为HTTP方法导出命名导出

Next.js 最新版中NextAuth登录路由报错解决方案

我在学习Next.js Airbnb克隆项目,教程采用旧实验版本,我使用最新版Next.js,对API路由机制不太熟悉。注册功能可正常运行,但登录时出现报错:

error Detected default export in 'E:\Program\airbnb\app\api\auth[...nextauth]\route.ts'. Export a named export for each HTTP method instead.

路由结构

路由路径

相关代码文件

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

export const authOptions: AuthOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID as string,
            clientSecret: process.env.GITHUB_SECRET as string
        }),
        GoogleProvider({
            clientId: process.env.GOOGLE_ClIENT_ID as string,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string
        }),
        CredentialsProvider({
            name: 'credentials',
            credentials: {
                email: {label: 'email', type: 'text'},
                password: {label: 'password', type: 'password'},
            },
            async authorize(credentials){
                if(!credentials?.email || !credentials?.password){
                    throw new Error('Invalid Credentials')
                }

                // 查询用户账号
                const user = await prisma.user.findUnique({
                    where: {
                        email: credentials.email,
                    },
                });

                // 验证用户及密码存在性
                if(!user || !user?.hashedPassword){
                    throw new Error('Invalid Credentials')
                }

                const isCorrectPassword = await bcrypt.compare(
                    credentials.password,
                    user.hashedPassword
                );

                if(isCorrectPassword){
                    throw new Error('Invalide Credentials')
                }

                return user
            }
        })
    ],

    pages: {
        signIn: '/',
    },
    debug: process.env.NODE_ENV === 'development',
    session: {
        strategy: 'jwt'
    },
    secret: process.env.NEXTAUTH_SECRET
   
}

export default NextAuth

register/route.js

export async function POST(request: Request) {
  const body = await request.json();
  const { email, name, password } = body;

  const hashedPassword = await bcrypt.hash(password, 12);

  const user = await prisma.user.create({
    data: {
      email,
      name,
      hashedPassword,
    },
  });

  return NextResponse.json(user);
}

LoginModal.ts 登录逻辑

const onSubmit: SubmitHandler<FieldValues> = (data) => {
    setIsLoading(true)
   
    signIn('credentials',{
      ...data,
      redirect: false,
    })
    .then((callback) => {
      setIsLoading(false)

      if(callback?.ok){
        toast.success('Logged In')
        router.refresh()
        loginModal.onClose()
      }

      if(callback?.error){
        toast.error(callback.error)
      }

    })
  }

报错原因及修复方案

核心问题

最新版Next.js的App Router要求API路由必须使用命名导出对应HTTP方法(如GET、POST),不能使用默认导出。你当前的[...nextauth]/route.js用了export default NextAuth,违反了App Router的规范。

修复步骤

  1. 修改NextAuth路由导出方式
    将[...nextauth]/route.js中的默认导出替换为GET和POST方法的命名导出:
// 替换原来的 export default NextAuth
export const GET = NextAuth(authOptions);
export const POST = NextAuth(authOptions);
  1. 修正CredentialsProvider逻辑错误
    代码中存在拼写和逻辑反转问题:
const isCorrectPassword = await bcrypt.compare(
    credentials.password,
    user.hashedPassword
);

// 原逻辑错误:密码正确时抛出错误,改为密码不正确时抛出
if(!isCorrectPassword){
    throw new Error('Invalid Credentials')
}
// 同时修正拼写错误:Invalide → Invalid

原理说明

旧版本NextAuth适配Pages Router时支持默认导出,而最新版Next.js的App Router强制要求API路由通过命名导出对应HTTP方法的函数来处理请求,这样才能正确匹配并处理登录相关的GET/POST请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:22:38