Server Side Locale

Middleware

Usage

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

const handleI18nRouting = createMiddleware(routing);
const response = handleI18nRouting(request);

Prefix-based routing

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:

  1. A locale prefix is present in the pathname (e.g. /en/about)
  2. A cookie is present that contains a previously detected locale
  3. A locale can be matched based on the accept-language header
  4. As a last resort, the defaultLocale is used

To 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.

No locale

Useful Hook

useLocale

import { useLocale } from "next-intl";
const locale = useLocale();

request.ts

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()