Next.js 14 App Router如何替代getServerSideProps获取当前Locale?
在Next.js 14 App Router中获取当前Locale的方案
针对你从Pages Router迁移到App Router后无法通过getServerSideProps获取locale的问题,以下是几种实用的实现方式:
1. 服务器组件中通过请求头获取Locale
你的Page组件默认是服务器组件,可以直接使用next/headers提供的headers()函数从请求头中提取next-locale字段(Next.js国际化路由会自动注入这个请求头):
// src/app/somepage/page.tsx import { headers } from 'next/headers'; const getContent = async function(lang: string){ // 添加cache: 'no-store'保持与getServerSideProps一致的服务端动态获取行为 const res = await fetch(`https://jsonplaceholder.typicode.com/todos/1?lang=${lang}`, { cache: 'no-store' }); const data = await res.json(); return data; } export default async function Page() { const headersList = headers(); // 读取next-locale,设置默认值适配你的项目配置 const locale = headersList.get('next-locale') || 'en'; const data = await getContent(locale); return <div>TEST!!! {data.title}</div>; }
2. 结合next-i18next获取Locale(兼容原有翻译逻辑)
如果你继续使用next-i18next,其适配App Router的版本可以通过getServerTranslations同时获取locale和翻译资源,完全替代原serverSideTranslations的功能:
// src/app/somepage/page.tsx import { getServerTranslations } from 'next-i18next/serverSideTranslations'; const getContent = async function(lang: string){ const res = await fetch(`https://jsonplaceholder.typicode.com/todos/1?lang=${lang}`, { cache: 'no-store' }); const data = await res.json(); return data; } export default async function Page() { // 获取locale和翻译资源,参数与原serverSideTranslations一致 const { locale } = await getServerTranslations(['common', 'header']); const data = await getContent(locale); return <div>TEST!!! {data.title}</div>; }
3. 客户端组件中使用useLocale钩子
如果你的页面是客户端组件(添加了'use client'指令),可以使用Next.js自带的useLocale钩子(需确保已配置国际化路由):
// src/app/somepage/page.tsx 'use client'; import { useLocale } from 'next/navigation'; import { useState, useEffect } from 'react'; const getContent = async function(lang: string){ const res = await fetch(`https://jsonplaceholder.typicode.com/todos/1?lang=${lang}`); const data = await res.json(); return data; } export default function Page() { const locale = useLocale(); const [data, setData] = useState<{ title?: string } | null>(null); useEffect(() => { async function fetchData() { const result = await getContent(locale); setData(result); } fetchData(); }, [locale]); return data ? <div>TEST!!! {data.title}</div> : <div>Loading...</div>; }
注意事项
- 服务器组件中使用
headers()只能在服务端执行,无法在客户端渲染阶段调用。 - 如果需要保持原
getServerSideProps的动态请求行为,记得在fetch中添加cache: 'no-store',避免Next.js自动缓存请求结果。 - 确保你的Next.js项目已正确配置国际化路由(在
next.config.js中设置i18n字段)。
内容的提问来源于stack exchange,提问作者MilMike
相关产品推荐
相关产品推荐

