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

