# Fumadocs Core (the core library of Fumadocs): Meilisearch
URL: /zh-TW/docs/headless/search/meilisearch
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/headless/search/meilisearch.zh-TW.mdx

將 Meilisearch 與 Fumadocs 整合

[Meilisearch](https://www.meilisearch.com) 是一款開源搜尋引擎，支援錯字容忍度與篩選功能。您可以自行架設，也可以使用 Meilisearch Cloud。

## 設定 [#setup]

安裝相依套件：

```package-install
meilisearch
```

### API 金鑰 [#api-keys]

請透過[自行架設](https://www.meilisearch.com/docs/learn/self_hosted/getting_started_with_self_hosted_meilisearch)或使用 [Meilisearch Cloud](https://www.meilisearch.com/cloud) 啟動 Meilisearch 執行個體，並將其認證資訊儲存在 `.env.local` 中 (在 Vite 框架中請將 `NEXT_PUBLIC_` 改為 `VITE_`，在 Astro 中則改為 `PUBLIC_`) ：

```dotenv
NEXT_PUBLIC_MEILISEARCH_HOST="URL of your instance"
NEXT_PUBLIC_MEILISEARCH_SEARCH_KEY="search API key"
MEILISEARCH_ADMIN_KEY="Default Admin API Key"
```

搜尋金鑰會暴露在瀏覽器中，因此請[建立一組](https://www.meilisearch.com/docs/learn/security/basic_security)只能搜尋 `docs` 索引的金鑰。管理員金鑰則請妥善保管，切勿公開。

### 同步文件 [#sync-documents]

預先算繪 `static.json` 路由，在建置時匯出搜尋文件，並於每次建置後透過指令碼將其同步至 Meilisearch：

```ts tab="Next.js" title="app/static.json/route.ts"
import { source } from '@/lib/source';
import { toDocuments } from 'fumadocs-core/search/meilisearch';

export const revalidate = false;

export async function GET() {
  return Response.json(await toDocuments(source));
}

```

```ts tab="Next.js" title="scripts/sync-content.ts"
import * as fs from 'node:fs/promises';
import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch';
import { Meilisearch } from 'meilisearch';

// Next.js writes it under `route-cache` when built with an adapter, like on Vercel
const [file] = await Array.fromAsync(fs.glob('.next/server/{app,route-cache/*/*/$}/static.json.body'));
const records = JSON.parse(await fs.readFile(file, 'utf-8')) as DocumentRecord[];

const client = new Meilisearch({
  host: process.env.NEXT_PUBLIC_MEILISEARCH_HOST!,
  apiKey: process.env.MEILISEARCH_ADMIN_KEY!,
});

await sync(client, {
  indexName: 'docs',
  documents: records,
});

console.log(`search updated: ${records.length} records`);

```

```json tab="Next.js" title="package.json"
{
  "scripts": {
    "build": "next build && node --env-file-if-exists=.env.local scripts/sync-content.ts"
  }
}
```

```ts tab="React Router" title="app/routes/static.json.ts"
import { source } from '@/lib/source';
import { toDocuments } from 'fumadocs-core/search/meilisearch';

export async function loader() {
  return Response.json(await toDocuments(source));
}

```

```ts tab="React Router" title="app/routes.ts"
import { index, route, type RouteConfig } from '@react-router/dev/routes';

export default [
  index('routes/home.tsx'),
  route('static.json', 'routes/static.json.ts'), // [!code ++:1]
] satisfies RouteConfig;

```

```ts tab="React Router" title="scripts/sync-content.ts"
import * as fs from 'node:fs/promises';
import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch';
import { Meilisearch } from 'meilisearch';

const records = JSON.parse(await fs.readFile('build/client/static.json', 'utf-8')) as DocumentRecord[];

const client = new Meilisearch({
  host: process.env.VITE_MEILISEARCH_HOST!,
  apiKey: process.env.MEILISEARCH_ADMIN_KEY!,
});

await sync(client, {
  indexName: 'docs',
  documents: records,
});

console.log(`search updated: ${records.length} records`);

```

```json tab="React Router" title="package.json"
{
  "scripts": {
    "build": "react-router build && node --env-file-if-exists=.env.local scripts/sync-content.ts"
  }
}
```

```ts tab="TanStack Start" title="src/routes/static[.]json.ts"
import { createFileRoute } from '@tanstack/react-router';
import { source } from '@/lib/source';
import { toDocuments } from 'fumadocs-core/search/meilisearch';

export const Route = createFileRoute('/static.json')({
  server: {
    handlers: {
      GET: async () => Response.json(await toDocuments(source)),
    },
  },
});

```

```ts tab="TanStack Start" title="vite.config.ts"
import { tanstackStart } from '@tanstack/react-start/plugin/vite';
import { nitro } from 'nitro/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    tanstackStart({
      prerender: {
        enabled: true,
      },
      pages: [ // [!code ++:3]
        { path: '/static.json' }
      ],
    }),
    nitro({
      preset: 'vercel',
    }),
  ],
});

```

```ts tab="TanStack Start" title="scripts/sync-content.ts"
import * as fs from 'node:fs/promises';
import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch';
import { Meilisearch } from 'meilisearch';

const records = JSON.parse(await fs.readFile('.vercel/output/static/static.json', 'utf-8')) as DocumentRecord[];

const client = new Meilisearch({
  host: process.env.VITE_MEILISEARCH_HOST!,
  apiKey: process.env.MEILISEARCH_ADMIN_KEY!,
});

await sync(client, {
  indexName: 'docs',
  documents: records,
});

console.log(`search updated: ${records.length} records`);

```

```json tab="TanStack Start" title="package.json"
{
  "scripts": {
    "build": "vite build && node --env-file-if-exists=.env.local scripts/sync-content.ts"
  }
}
```

```ts tab="Waku" title="src/pages/_api/static.json.ts"
import { source } from '@/lib/source';
import { toDocuments } from 'fumadocs-core/search/meilisearch';

export async function GET() {
  return Response.json(await toDocuments(source));
}

export async function getConfig() {
  return {
    render: 'static' as const,
  } as const;
}

```

```ts tab="Waku" title="scripts/sync-content.ts"
import * as fs from 'node:fs/promises';
import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch';
import { Meilisearch } from 'meilisearch';

const records = JSON.parse(await fs.readFile('dist/public/static.json', 'utf-8')) as DocumentRecord[];

const client = new Meilisearch({
  host: process.env.VITE_MEILISEARCH_HOST!,
  apiKey: process.env.MEILISEARCH_ADMIN_KEY!,
});

await sync(client, {
  indexName: 'docs',
  documents: records,
});

console.log(`search updated: ${records.length} records`);

```

```json tab="Waku" title="package.json"
{
  "scripts": {
    "build": "waku build && node --env-file-if-exists=.env.local scripts/sync-content.ts"
  }
}
```

```ts tab="Astro" title="src/pages/static.json.ts"
import type { APIRoute } from 'astro';
import { source } from '@/lib/source';
import { toDocuments } from 'fumadocs-core/search/meilisearch';

export const prerender = true;

export const GET: APIRoute = async () => Response.json(await toDocuments(source));

```

```ts tab="Astro" title="scripts/sync-content.ts"
import * as fs from 'node:fs/promises';
import { type DocumentRecord, sync } from 'fumadocs-core/search/meilisearch';
import { Meilisearch } from 'meilisearch';

const records = JSON.parse(await fs.readFile('dist/static.json', 'utf-8')) as DocumentRecord[];

const client = new Meilisearch({
  host: process.env.PUBLIC_MEILISEARCH_HOST!,
  apiKey: process.env.MEILISEARCH_ADMIN_KEY!,
});

await sync(client, {
  indexName: 'docs',
  documents: records,
});

console.log(`search updated: ${records.length} records`);

```

```json tab="Astro" title="package.json"
{
  "scripts": {
    "build": "astro build && node --env-file-if-exists=.env.local scripts/sync-content.ts"
  }
}
```

`sync()` 會設定索引並取代其中的文件；在新文件完成索引前，舊文件仍可供搜尋。`build` 指令碼會在每次建置時同步，請在您的部署平台上設定相同的變數。

### 搜尋 UI [#search-ui]

實作 UI 時，您可以考慮以下幾種方式：

* 使用 [Fumadocs UI 搜尋對話方塊](/docs/next/search/meilisearch)。

* 使用內建的搜尋用戶端 hook 自行打造：

  ```ts twoslash
  import { Meilisearch } from 'meilisearch';
  import { useMeilisearch } from 'fumadocs-core/search/client';

  const client = new Meilisearch({
    host: 'host url',
    apiKey: 'search api key',
  });

  const { search, onSearchChange, isLoading, data } = useMeilisearch({
    client,
    indexName: 'docs',
  });
  ```

  ### $Fumadocs

  | Prop        | Type                              | Description                              |
  | ----------- | --------------------------------- | ---------------------------------------- |
  | `client`    | `Meilisearch`                     | Meilisearch client with a search API key |
  | `indexName` | `string`                          |                                          |
  | `tag?`      | `string \| string[] \| undefined` | Filter results with specific tag(s).     |
  | `locale?`   | `string \| undefined`             | Filter results by locale.                |

* 直接使用 Meilisearch 的官方用戶端。

## 選項 [#options]

### 標籤篩選 [#tag-filter]

若要設定標籤篩選，請在 `static.json` 路由中將 `tag` 傳入 `toDocuments()`：

```ts
toDocuments(source, { tag: (page) => page.slugs[0] });
```

接著更新您的搜尋用戶端：

* **Fumadocs UI**：在搜尋 UI 中啟用[標籤篩選](/docs/next/search/meilisearch#tag-filter)。
* **搜尋用戶端**：將標籤傳入 `useMeilisearch()`。

  ```ts
  import { useMeilisearch } from 'fumadocs-core/search/client';

  const { search, onSearchChange, isLoading, data } = useMeilisearch({
    tag: '<your tag value>', // [!code ++]
    // ...
  });
  ```

### 國際化 [#internationalization]

文件會包含所屬頁面的語系，傳入 `locale` 即可搜尋特定語言：

```ts
import { useI18n } from 'fumadocs-ui/contexts/i18n';
import { useMeilisearch } from 'fumadocs-core/search/client';

const { locale } = useI18n();
const { search, onSearchChange, isLoading, data } = useMeilisearch({
  locale, // [!code ++]
  // ...
});
```

### 索引設定 [#index-settings]

`sync()` 只會設定 `searchableAttributes` 和 `filterableAttributes`，其他設定 (例如同義詞與錯字容忍度) 則會維持不變。您可以透過 Meilisearch 儀表板或 `meilisearch` 用戶端調整這些設定。

## 運作原理 [#under-the-hood]

每個標題與段落都是一份文件，並附帶頁面標題、URL 與 Breadcrumb。只有 `content` 可供搜尋，搜尋用戶端會依頁面將結果分組。

| 屬性        | 說明                        |
| --------- | ------------------------- |
| `type`    | `page`、`heading` 或 `text` |
| `content` | 頁面標題、標題或段落                |
| `heading` | 所屬標題的 ID (選用)             |
| `tag`     | 用於篩選結果的標籤 (選用)            |
| `locale`  | 頁面的語系 (選用)                |