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

Next.js Pages目录下Middleware传参引发404问题求助

解决Next.js中间器重写后出现404的问题

1. 修正中间件的重写路径与匹配规则

404最可能的原因是中间件重写逻辑错误,导致请求被导向不存在的页面。需确保重写目标指向根路径/(对应pages/index.js),同时限制中间件仅作用于根路径:

import { NextResponse } from 'next/server';

export function middleware(request) {
  // 安全获取geo信息(本地开发环境geo可能为undefined)
  const country = request.geo?.country || 'unknown';
  const city = request.geo?.city || 'unknown';

  // 基于原URL构造新地址,保留原有查询参数并添加geo信息
  const newUrl = new URL(request.url);
  newUrl.searchParams.set('country', country);
  newUrl.searchParams.set('city', city);

  // 重写至根路径,而非自定义的非标准路径
  return NextResponse.rewrite(newUrl);
}

// 仅匹配根路径,避免影响其他页面路由
export const config = {
  matcher: '/',
};

注意:不要将重写路径设为/index或其他非标准路径,pages目录下的index.js对应的路由是/。

2. 检查getServerSideProps的实现逻辑

确保index.js中的getServerSideProps正确处理查询参数,且没有抛出未捕获的错误(虽通常导致500而非404,但仍需排查):

export async function getServerSideProps(context) {
  const { country = 'unknown', city = 'unknown' } = context.query;
  return { props: { country, city } };
}

export default function Home({ country, city }) {
  return (
    <div>
      <h1>Home</h1>
      <p>当前地区:{city}, {country}</p>
    </div>
  );
}

3. 排查版本兼容性与缓存问题

  • 若使用Next.js 13+的App Router,确保中间件遵循Pages Router的兼容规则,使用next/server导出中间件,而非旧版模块。
  • 重启开发服务器并清除Next.js缓存:
    rm -rf .next
    npm run dev
    

本地开发环境的缓存可能导致路由规则不生效,引发404。

4. 避免geo信息获取中断重写流程

本地开发环境中,request.geo可能为undefined,需添加可选链或默认值,防止因错误导致重写逻辑失败,进而导向错误路径。

内容的提问来源于stack exchange,提问作者Life Smile

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 08:03:56