import createMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";
const handleI18nRouting = createMiddleware(routing);
const response = handleI18nRouting(request);
By default, prefix-based routing is used to determine the locale of a request. In this case, the locale is detected based on these priorities:
/en/about
)accept-language
headerdefaultLocale
is usedTo change the locale, users can visit a prefixed route. This will take precedence over a previously matched locale that is saved in a cookie or the accept-language
header and will update a previous cookie value.
/about
。handleI18nRouting(request)
检测到路径缺少语言前缀 → 立即返回 NextResponse.redirect('/en/about', 307)
return response
,请求在这一层就结束了,浏览器收到 307 后自动跟随。/en/about
发起新请求。request.nextUrl.pathname
已带 en
:
handleI18nRouting
发现前缀齐全 → 返回 NextResponse.next()
,页面才真正渲染。import { useLocale } from "next-intl";
const locale = useLocale();
src/i18n/request.ts
- 在 “服务器端” 把“我该用哪种语言、加载哪份字典”告诉 next-intl
角色 | 做什么 | 什么时候被调用 |
---|---|---|
middleware.ts | 在 Edge 上根据 URL 或 cookie 把请求重定向到正确的 /en/* / /zh/* ,并在响应头里写 x-next-intl-locale |
每次 HTTP 请求 刚到达 Vercel/Node 时 |
i18n/request.ts |
在 应用服务器代码(Server Components / Server Actions / route handlers)里,根据刚才确定的 locale 返回 {locale, messages} 给 next-intl |
当你在 服务器端 调用 getTranslations() 、getLocale() 、useTranslations() 时 |