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

Next Auth中间件模块解析错误:NextResponse已重复声明

解决Next Auth中间件NextResponse重复声明错误

这个错误是因为Next Auth的middleware模块和你的代码重复导入了NextResponse,或是版本不兼容导致的内部冲突。以下是几种可行的解决方法:

1. 统一NextResponse导入,避免重复

如果你的中间件文件里自己导入了NextResponse,不要同时直接导出Next Auth的默认中间件。改用withAuth包裹自定义逻辑,确保只导入一次NextResponse:

import { withAuth } from "next-auth/middleware";
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export default withAuth(
  (req: NextRequest) => {
    // 写你的重定向逻辑,比如根据会话状态跳转
    const isLoggedIn = !!req.nextauth.token;
    const targetPath = req.nextUrl.pathname;

    // 未登录访问受保护页面跳登录页
    if (!isLoggedIn && targetPath.startsWith('/dashboard')) {
      return NextResponse.redirect(new URL('/login', req.url));
    }
    // 已登录访问登录页跳首页
    if (isLoggedIn && targetPath === '/login') {
      return NextResponse.redirect(new URL('/', req.url));
    }
  },
  {
    callbacks: {
      authorized: ({ token }) => !!token,
    },
  }
);

// 配置需要拦截的路径
export const config = {
  matcher: ['/dashboard/:path*', '/login'],
};

2. 升级依赖版本

这个问题多出现于Next Auth和Next.js版本不兼容的情况,执行命令升级到最新稳定版:

npm update next-auth next
# yarn用户用下面的命令
yarn upgrade next-auth next

3. 不要直接导出Next Auth的默认中间件

避免直接写export { default } from "next-auth/middleware";,这种写法容易和自定义导入产生冲突,始终用withAuth包裹自己的中间件逻辑来实现会话校验和重定向。

内容的提问来源于stack exchange,提问作者Илья Маковецкий

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:49:59