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

NextJS 14中next-intl与next/link导航异常问题求助

NextJS 14 + next-intl 跳转路径缺失语言前缀及DOM错误解决

问题描述

我在NextJS 14中集成next-intl实现多语言支持,预期路径格式为www.next.com/de或www.next.com/en。但使用以下代码跳转时:

<NextLink href="/support-us">{t("About us")}</NextLink>

实际跳转到了无语言前缀的/support-us,同时抛出错误:

NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

相关代码

middleware.ts

import createMiddleware from "next-intl/middleware";
import { locales } from "./i18n";

export default createMiddleware({
  // 支持的语言列表
  locales,

  // 无匹配语言时使用的默认值
  defaultLocale: "en",
});

export const config = {
  // 匹配国际化路径
  matcher: ["/", "/(en|it|de|nl|fr|sv|es|nb|pt|pl)/:path*"],
};

i18n 文件

import { notFound } from "next/navigation";
import { getRequestConfig } from "next-intl/server";

interface Language {
  symbol: string;
  name: string;
}

export const supportedLanguages: Language[] = [
  { symbol: "EN", name: "English" },
  { symbol: "DE", name: "Deutsch" },
];

const languageSymbolsLowercase: string[] = supportedLanguages.map((lang) =>
  lang.symbol.toLowerCase()
);

const initialLocales: string[] = [];

const combinedLocales: string[] = [
  ...initialLocales,
  ...languageSymbolsLowercase,
];

export const locales: string[] = combinedLocales;

export default getRequestConfig(async ({ locale }) => {
  if (!locales.includes(locale)) notFound();

  return {
    messages: (await import(`../messages/${locale}.json`)).default,
  };
});

解决方案

next-intl 自带的 Link 组件会自动根据当前语言环境补全路径前缀,无需手动处理。

先导入组件:

import Link from 'next-intl/link';

修改跳转代码:

<Link href="/support-us">{t("About us")}</Link>

该组件会自动生成如/en/support-us的正确路径,解决前缀缺失问题。

2. 对齐 middleware 匹配规则与支持的语言列表

当前middleware.ts的matcher包含了it|nl|fr等语言,但你的supportedLanguages仅配置了en和de。建议将matcher中的语言列表与locales数组保持一致,避免无效匹配:

// 修改 middleware.ts 中的 matcher
export const config = {
  matcher: ["/", "/(en|de)/:path*"],
};

3. 修复路径前缀后排查DOM错误

路径缺失导致的404页面,可能触发导航过程中的DOM操作异常。修复路径前缀后,removeChild错误通常会自动消失。如果问题仍存在,检查页面组件在导航前后的DOM结构,确保组件卸载逻辑正常,无残留节点操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:04:51