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
相关产品推荐
相关产品推荐

