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

如何借助next-intl实现基于语言的Next.js元数据配置?

解决Next.js + next-intl 多语言元数据报错问题

问题原因

useTranslations是React Hook,仅能在组件渲染阶段调用,但metadata是在组件外部声明的服务器端初始化逻辑,此时requestAsyncStorage还未就绪,因此触发报错。

解决方案

方案一:使用generateMetadata函数(App Router推荐方案)

这是Next.js官方推荐的元数据生成方式,配合next-intl的服务器端翻译方法,完全适配服务端执行环境:

import { getTranslations } from 'next-intl/server';

// 异步生成元数据,直接从params获取locale
export async function generateMetadata({ params }) {
  const t = await getTranslations({ locale: params.locale, namespace: 'Page' });
  
  return {
    title: t('pageTitle'),
    description: t('pageDescription')
  };
}

export default function Page({ params }) {
  // 页面组件内容
}
  • 注意:多语言文件(en.json、tr.json)需提前配置对应翻译键,比如"pageTitle": "首页"(zh.json)、"pageTitle": "Home Page"(en.json)。

方案二:客户端动态设置元数据(适合非SSR场景)

如果不需要服务器端渲染元数据,可在客户端组件中通过useEffect动态修改:

'use client';
import { useTranslations } from 'next-intl';
import { useEffect } from 'react';

export default function Page({ params }) {
  const t = useTranslations('Page');

  useEffect(() => {
    document.title = t('pageTitle');
  }, [t]);

  return (
    // 页面组件内容
  );
}
  • 必须添加'use client'指令,确保代码在客户端执行。

额外注意

确保路由结构已配置locale参数(如app/[locale]/page.js),保证params.locale能正确获取当前语言标识。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:32:38