Next.js

路由與導向

本頁說明 Intor 在 Next.js 專案中的路由整合方式。


本節延續 Next.js 快速開始,進一步加入 Routing 設定。

專案結構

page.tsx
U

intor-config.ts
M
proxy.ts
U

整合步驟

♯1 建立動態路由

app/ 中新增動態路由資料夾 [locale],並在底下新增 page.tsx

page.tsx 內容可直接沿用前一章的 使用範例 ,此處不再重複說明。

page.tsx
U

♯2 套用 Inbound Routing

src/ 底下新增 proxy.ts,並使用 createIntorHandler 介入請求流程。

proxy.ts
U
import { createIntorHandler } from "intor/next";
import { intorConfig } from "@/i18n/intor-config";

export const proxy = createIntorHandler(intorConfig);

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

♯3 啟用 Routing 設定

在設定檔中啟用 Routing 行為。

詳見:設定檔/Routing

intor-config.ts
M
import { defineIntorConfig } from "intor/config";

export const intorConfig = defineIntorConfig({
  // ...
  routing: { localePrefix: "all" },
});

設定完成後,請求將依據 Routing 規則自動導向至對應的語系路徑。

♯4 使用導航工具

以下工具用於描述與執行具備語系意識的導覽行為。
其組合規則請參考:導航意圖

<Link />

基於 Next.js 的 next/link

<Link href="/path" locale="en">English</Link>

useRouter

基於 Next.js 的 useRouter

const { push } = useRouter();
push("/path", { locale: "en" });

redirect

基於 Next.js 的 redirect

redirect(intorConfig, "/path", { locale: "en" });