Next.js 13(App路由)中无效中间件问题求助
Next.js 13 App路由中间件无效问题解决方法
错误原因很明确:你的config对象里的matcher数组中,'login'这个路径没有以斜杠/开头,违反了Next.js中间件路径匹配的要求——所有匹配路径必须以/开头。
只需要修改matcher数组里的路径,把'login'改成'/login'即可,修改后的完整代码如下:
import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; export function middleware(request: NextRequest) { 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: ['/','/profile', '/login', '/signup'], };
修改后,中间件的路径匹配规则符合要求,就能正常运行了。
内容的提问来源于stack exchange,提问作者coder
相关产品推荐
相关产品推荐

