Next.js中如何在middleware.js验证动态路由参数
解决方案
你的问题出在**request.nextUrl.pathname对应的是实际请求路径(比如/US/NY),而不是路由文件里的/[country_code]格式**,所以判断startsWith('/[country_code]')永远不会生效。下面是具体的实现步骤和代码:
核心思路
- 拆分请求路径的片段,提取动态路由对应的
country_code和state_code - 定义允许的国家/州代码列表
- 验证参数合法性,不合法则重定向(或返回自定义响应)
修改后的Middleware代码
import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { // 拆分路径片段,过滤掉空字符串(处理开头的/) const pathSegments = request.nextUrl.pathname.split('/').filter(seg => seg) // 定义允许的国家和州代码 const allowedCountries = ['US', 'CA'] const allowedStates = ['NY', 'FL'] // 处理一级路径:/[country_code] if (pathSegments.length === 1) { const countryCode = pathSegments[0] if (!allowedCountries.includes(countryCode.toUpperCase())) { // 重定向到首页,或自定义错误页面 return NextResponse.redirect(new URL('/', request.url)) } } // 处理二级路径:/[country_code]/[state_code] if (pathSegments.length === 2) { const [countryCode, stateCode] = pathSegments const isValidCountry = allowedCountries.includes(countryCode.toUpperCase()) const isValidState = allowedStates.includes(stateCode.toUpperCase()) if (!isValidCountry || !isValidState) { return NextResponse.redirect(new URL('/', request.url)) } } return NextResponse.next() } export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], }
代码说明
pathSegments = request.nextUrl.pathname.split('/').filter(seg => seg):把/US/NY拆分成['US', 'NY'],过滤空字符串避免开头的/导致的空元素- 分别处理一级和二级路径的验证逻辑,确保
country_code只能是US/CA,state_code只能是NY/FL - 不合法的请求会被重定向到首页,你可以根据需求修改重定向目标(比如自定义403页面)
内容的提问来源于stack exchange,提问作者Sethuraman Srinivasan
相关产品推荐
相关产品推荐

