Next.js reference
18ways.config.*
在你的应用根目录中创建 18ways.config.ts、18ways.config.js 或 18ways.config.cjs,并在那里导出
your 18ways 配置。
import type { WaysConfig } from '@18ways/next/config';
export default {
apiKey: process.env.NEXT_PUBLIC_18WAYS_PUBLIC_API_KEY,
baseLocale: 'en-GB',
router: 'app', // 'app', 'path', or 'none' depending on if you use app router, path router, or if you don't want the router to sync with locale at all
} satisfies WaysConfig;withWays()
从 @18ways/next/config 导入,并在 next.config.js 中调用它。
import { withWays } from '@18ways/next/config';当 18ways.config.* 存在时,withWays() 会自动加载它。对于 router: 'path',它会返回原生的 Next i18n 配置,并禁用语言环境检测。对于 router: 'app' 和
router: 'none',它会注入从 @18ways/next/server 直接导入所需的别名。
Common options:
| Option | Type | Notes |
|---|---|---|
apiKey | string | Required. |
baseLocale | string | 用于路由的源语言区域和默认语言区域。 |
路由器 | ‘app’ | ‘path’ | ‘none’ | 区域路由模式。当其他路由器已经拥有区域 URL 时,请使用 none。 |
acceptedLocales | string[] | 显式地区列表。对于 path 是必需的,其他情况下可选。请将 path 模式与您 18ways 仪表板中启用的语言保持同步。 |
域 | Array<{domain, defaultLocale}> | 可选的域路由映射。 |
localeParamName | string | App Router 区域设置段参数。默认为 lang。 |
persistLocaleCookie | boolean | ((request) => boolean) | 服务器和客户端语言区域更改的 locale-cookie 持久化策略。 |
cacheTtl | number | Cache TTL for adapter requests. |
fetcher | typeof fetch | Custom fetch implementation. |
init(config)
Import from @18ways/next/server.
当你想显式绑定一个配置对象时使用它。
WaysRoot
在将 next.config.js 用 withWays(...) 包裹后,请在布局中直接从 @18ways/next/server 导入 WaysRoot。
在你的布局中使用 WaysRoot,这样适配器就能为当前请求注入运行时状态。
在 App Router 的区域设置路由中,这通常意味着 app/[lang]/layout.tsx。
getLocale()
在服务器上解析当前区域设置。当你需要在 WaysRoot 之外使用区域设置状态时,这是要用的辅助函数,例如在仅限服务器端的 SEO 辅助函数或其他与请求绑定的服务器代码中。
htmlAttrs()
htmlAttrs() resolves the current lang and dir values for the document element.
generateWaysMetadata()
Use generateWaysMetadata() inside generateMetadata() when you want translated titles,
descriptions, and locale-aware canonical or alternate URLs.
proxy.ts
对于 router: 'app',proxy.ts 是用于请求时语言环境重定向的推荐入口点。
从 @18ways/next/proxy 重新导出,以处理 / -> /{locale} 和域名规范化。
export { default, config } from '@18ways/next/proxy';如果你已经有自己的项目 proxy.ts 或 middleware.ts,请使用
getWaysProxyResponse(request),并在执行其余逻辑之前将其返回。
Client helpers
Import from @18ways/next/client.
useLocale()
Read and change the current locale. This is the hook you pair with LanguageSwitcher or your own
custom selector UI.
useRouter()
围绕 Next 导航的区域设置感知包装器。传入 locale="fr-FR" 以强制跳转到本地化目标,或
locale={false} 以强制跳转到非本地化目标。
Link
围绕 next/link 的本地化感知包装器,具有与 useRouter() 相同的覆盖模型。
useUnlocalizedPathname()
Read the current pathname without the locale prefix.
useLocalizedHref()
用于将内部 href 转换为当前本地化 href 的底层辅助函数。
Path routing config
在 router: 'app' 模式下,适配器会遵循你的路由树:
app/[lang]/...下的路由已本地化- 该区段之外的路线保持未本地化
Link、useRouter() 和 setLocale() 默认会将内部路由视为已本地化。只有在你需要明确指向未本地化路由时,才使用
locale={false}。