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

NextJS自定义404页面useTranslation翻译失效求助

自定义404页面翻译失效问题排查与解决

问题根源

  • 自定义404页面(404.tsx)未实现数据获取方法注入翻译资源,useTranslation无法拿到对应语言的翻译数据
  • 全局错误页面(_error.tsx)在接管错误渲染流程时,未注入翻译资源,若404场景走该页面也会导致翻译失效

解决方案

1. 为404.tsx添加getStaticProps方法

在404.tsx文件末尾添加以下代码,用于在构建阶段获取对应语言的翻译资源:

export async function getStaticProps({ locale }: { locale: string }) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['common'])),
    },
  };
}

注:['common']需与t('page-not-found')使用的翻译命名空间保持一致。

2. 修改_error.tsx的getInitialProps注入翻译资源

在_error.tsx的初始化方法中加入翻译资源获取逻辑,修改后的代码如下:

AppError.getInitialProps = async (ctx) => {
  const errorInitialProps: AppErrorProps =
    await NextErrorComponent.getInitialProps(ctx);
  errorInitialProps.hasGetInitialPropsRun = true;

  // 注入翻译资源
  const translations = await serverSideTranslations(ctx.locale || 'en', ['common']);

  if (ctx.err) {
    captureError(ctx.err);
    await flush(2000);
    return {
      ...errorInitialProps,
      ...translations,
    };
  }
  captureError(
    new Error(`_error.tsx getInitialProps missing data at path: ${ctx.asPath}`),
  );
  await flush(2000);

  return {
    ...errorInitialProps,
    ...translations,
  };
};

注:ctx.locale依赖Next.js的i18n配置,若项目默认语言不是en,请替换为对应语言标识。

3. 确认翻译资源文件完整性

检查public/locales/{语言标识}/common.json文件中是否存在page-not-found的翻译条目,示例:

  • 英文(en/common.json):"page-not-found": "Page Not Found"
  • 中文(zh/common.json):"page-not-found": "页面未找到"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:33:07