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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:19:51