Next.js 14.1.0中间件未触发:student路由保护失效问题排查
使用Next.js 14.1.0版本,在src目录下创建了middleware.js,src包含app、common、components子目录,app下有student子目录,尝试通过中间件保护student路由,但中间件未触发,怀疑配置缺失。相关文件内容如下:
middleware.js
import { NextResponse } from 'next/server' // This function can be marked `async` if using `await` inside export function middleware(request) { const path = request.nextUrl.pathname const isPublicPath = path === '/login' || path === '/signup' const token = request.cookies.get('token')?.value || '' if(isPublicPath && token){ return NextResponse.redirect(new URL('/' , request.nextUrl)) } if(!isPublicPath && !token){ return NextResponse.redirect(new URL('/login' , request.nextUrl)) } } export const config = { matcher: '/student/:path*', }
next.config.mjs
/** @type {import('next').NextConfig} */ const nextConfig = { // skipTrailingSlashRedirect: true, // trailingSlash: true, // output: 'export', api: { bodyParser: { sizeLimit: "20mb", }, }, images: { domains: ['20.78.10.88'], }, }; export default nextConfig;
jsconfig.json
{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }
确认中间件文件位置与命名:Next.js要求
middleware.js必须放在src根目录(当前位置正确),不能放在app或其他子目录下,同时检查文件名拼写是否为小写的middleware.js(大小写敏感)。修正matcher路径匹配规则:
当前matcher: '/student/:path*'理论上匹配/student及所有子路由,但可改为数组形式明确覆盖更多场景,避免路径匹配歧义:export const config = { matcher: ['/student', '/student/:path*'] }若后续开启
trailingSlash,需调整matcher为'/student/:path*/',确保访问带斜杠的路径也能触发中间件。验证中间件是否被加载:在middleware函数开头添加日志输出,重启开发服务器后访问student路由,查看终端是否有日志:
export function middleware(request) { console.log('中间件触发,当前路径:', request.nextUrl.pathname); // 原有逻辑... }若无日志输出,说明Next.js未识别到中间件,可尝试删除
.next缓存目录后重启服务,或检查项目结构是否符合App Router规范。排查静态导出与路由重写影响:确认next.config中未开启
output: 'export'(当前已注释),静态导出模式下中间件不会运行;同时检查是否有其他路由重写规则干扰student路径的匹配。检查token逻辑边界:当前逻辑中,若访问根路径
/且无token,会被重定向到/login,但这不是中间件未触发的直接原因。确保访问/student时,路径完全匹配matcher规则,且token判断逻辑没有意外跳过。
内容的提问来源于stack exchange,提问作者Umar Raza

