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

Next.js 13(App路由)中间件无效问题求助

问题分析与解决方案

核心错误原因

启动时出现的source does not start with / for route {"source":"signup"}错误,是因为middleware配置的matcher数组中,signup路径没有以斜杠/开头。Next.js要求路由匹配规则中的路径必须以/起始,无效的路径格式直接导致了Invalid middleware found的报错。

修正后的代码

只需要修改config对象里的matcher数组,给signup添加上开头的斜杠即可:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request : NextRequest)
{
    const path = request.nextUrl.pathname;

    const isPublicPath = path.includes('/login') || path.includes('/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', // 添加上起始斜杠
    ],
}

额外优化建议(可选)

当前判断isPublicPath使用path.includes()可能会匹配到意外路径(比如/login-abc这类包含关键词的非目标路径),如果需要更精确的路由匹配,可以改用严格相等判断:

const isPublicPath = path === '/login' || path === '/signup';

内容的提问来源于stack exchange,提问作者Sparsh Verma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:44:51