Next.js添加middleware.ts后出现NextResponse重复声明解析报错
解决:Module parse failed: Identifier 'NextResponse' has already been declared
问题原因
这个错误的核心是middleware.ts文件中存在NextResponse标识符的重复声明。虽然你贴出的代码里没有显式写import { NextResponse } from 'next/server',但next-auth/middleware内部已经引入并使用了这个变量,如果你的文件里残留了之前写的导入语句,或者版本不兼容导致内部命名冲突,就会触发这个错误。
修复步骤
清理冗余代码
确保你的middleware.ts文件只有以下代码,删除所有多余的导入、变量声明:export { default } from "next-auth/middleware" export const config = { matcher: [ "/bookings", "/directories", "/listingsFavs" ] };版本兼容性检查
若清理后仍报错,确认next-auth和Next.js版本匹配:Next.js 13+ 需搭配next-auth v4.20+。重新安装依赖修复:npm uninstall next-auth npm install next-auth@latest改用显式自定义(备选方案)
若默认导出方式仍有冲突,换用显式导入并自定义middleware逻辑:import { withAuth } from "next-auth/middleware"; import { NextResponse } from "next/server"; export default withAuth( (req) => { // 可添加自定义权限逻辑 return NextResponse.next(); }, { matcher: ["/bookings", "/directories", "/listingsFavs"] } );
内容的提问来源于stack exchange,提问作者demon Time
相关产品推荐
相关产品推荐

