# General Translation React SDKs (gt-react, gt-next, gt-react-native): App Router 中间件
URL: https://generaltranslation.com/zh/docs/react/nextjs/app-router-middleware.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何为 Next.js App Router 配置 General Translation 区域设置路由。

配置中间件、`[locale]` 根级段以及请求区域设置函数，以便 App Router 请求能解析到正确的本地化路由。

## 配置中间件 [#middleware]

在项目根目录下创建 `proxy.ts` (Next.js 15 及更早版本中为 `middleware.ts`) ：

```ts title="proxy.ts"
import { createNextMiddleware } from 'gt-next/middleware';

export default createNextMiddleware();

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next).*)'],
};
```

中间件会从 URL、Cookie、浏览器请求头或默认区域设置中检测区域设置，然后将请求重定向或改写为对应的本地化路由。

## 添加区域设置路由 [#locale-route]

将你的 App Router 页面移到 `app/[locale]` 下：

<Files>
  <Folder name="app">
    <Folder name="[locale]">
      <File name="layout.tsx" />

      <File name="page.tsx" />
    </Folder>
  </Folder>

  <File name="getLocale.ts" />

  <File name="proxy.ts" />
</Files>

该路由段会接收由中间件选择的区域设置。有关路由选项、[本地化路径别名](/docs/react/nextjs/reference/functions/create-next-middleware#path-config)以及[针对特定区域设置的页面实现](/docs/react/nextjs/reference/functions/create-next-middleware#route-overrides)，请参阅 [`createNextMiddleware`](/docs/react/nextjs/reference/functions/create-next-middleware)。

<Callout type="info">
  **请求时渲染：** 你可以将根布局保留在 `app/layout.tsx`，
  只把页面放到 `app/[locale]` 下。在根布局中调用
  [`getLocale`](/docs/react/nextjs/reference/functions/get-locale)；
  中间件会提供请求区域设置，因此你无需自定义 `getLocale.ts`。
  预渲染时请使用下面的请求函数，因为中间件不会在静态生成期间运行。
</Callout>

## 读取根级区域设置 [#root-locale]

在项目根目录下创建 `getLocale.ts`。`withGTConfig` 会自动检测到该文件。

```ts title="./getLocale.ts"
import { locale } from 'next/root-params';

export default async function getLocale() {
  return await locale();
}
```

根参数可在不读取请求头或 cookie 的情况下提供区域设置。

<Callout type="info">
  **Next.js 15.2–15.4：**`next/root-params` 在 Next.js 15.5 及更高版本中可用。在 15.2 至 15.4 中，请从 `next/server` 导入 `unstable_rootParams`，并改为返回 `(await unstable_rootParams())?.locale`。在 15.2 之前，根参数不以任何形式提供，因此请从请求中解析区域设置。
</Callout>

## 切换区域设置 [#locale-switching]

当访问者更改区域设置时，`gt-next` 会将该选择存储在 cookie 中，并且通常会通过 `router.refresh()` 刷新服务器组件。

如果访问者切换到默认区域设置，而当前 URL 解析到的是另一个区域设置，浏览器会重新加载，以便中间件重写 pathname。例如，当默认区域设置不带前缀时，`/fr/about` 会变成 `/about`。

## 拒绝不支持的区域设置 [#validate-locales]

默认情况下，如果请求的区域设置不受支持，系统会发出警告并回退到 `defaultLocale`。对于严格使用区域设置前缀的路由，请在 `app/[locale]/layout.tsx` 中验证路由参数，并调用 `notFound()`：

```tsx title="app/[locale]/layout.tsx"
import { isLocaleSupported } from 'gt-next';
import { notFound } from 'next/navigation';

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  if (!isLocaleSupported(locale)) {
    notFound();
  }

  return (
    <html lang={locale}>
      <body>{children}</body>
    </html>
  );
}
```

[`isLocaleSupported`](/docs/react/nextjs/reference/functions/is-locale-supported) 接受已配置的区域设置别名，并将该值缩小为 `string` 类型。中间件不会自动将未知路由段视为 404。

## Next steps

- /docs/react/nextjs/app-router-static-site-generation
- /docs/react/nextjs/registering-request-locales
- /docs/react/nextjs/cache-components
- /docs/react/nextjs/locale-alias-seo

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
