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

NextJS13本地化中间件导致URL查询参数丢失的解决方法

解决NextJS13本地化中间件丢失查询参数的问题

你的问题出在重定向逻辑里只拼接了路径部分,没有把请求的查询参数(search)包含进去。只要修改构造重定向URL的代码,追加查询参数即可解决。

修改后的完整中间件代码

import { NextFetchEvent, NextMiddleware, NextRequest, NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import { i18n } from "@/i18n.config";

let defaultLocale = "en-US";

function getLocale(request: NextRequest): string | undefined {
  const negotiatorHeaders: Record<string, string> = {};
  request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));

  // @ts-ignore locales are readonly
  const locales: string[] = i18n.locales;
  const languages = new Negotiator({ headers: negotiatorHeaders }).languages();

  const locale = match(languages, locales, defaultLocale);

  return locale;
}

export default function localisationMiddleware(middleware: NextMiddleware) {
  return async (request: NextRequest, event: NextFetchEvent) => {
    const pathname = request.nextUrl.pathname;

    const pathnameIsMissingLocale = i18n.locales.every(
      locale => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
    );

    if (pathnameIsMissingLocale) {
      const locale = getLocale(request);

      // 关键修改:追加查询参数 request.nextUrl.search
      return NextResponse.redirect(
        new URL(`/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}${request.nextUrl.search}`, request.url)
      );
    }

    return middleware(request, event);
  };
}

关键修改说明

在构造重定向URL时,末尾加上${request.nextUrl.search},这样原请求中的所有查询参数(比如?id=123&name=test)都会被完整保留到新的URL中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:30:22