Notion
使用 Fumadocs 發布 Notion 資料庫中的頁面。
@fumadocs/notion 會將 Notion 資料庫中的頁面載入為內容來源,並在伺服器端以 Fumadocs UI 算繪頁面中的區塊。
設定
npm install @fumadocs/notion @notionhq/client請在 Fumadocs UI 的樣式之後匯入它的樣式:
@import 'fumadocs-ui/css/neutral.css';
@import 'fumadocs-ui/css/preset.css';
@import '@fumadocs/notion/css/preset.css';Notion 資料庫
建立 Notion 整合,並將其連結至存放您頁面的資料庫。資料庫中的每一列即為一個頁面,並包含以下屬性:
- 標題屬性即為頁面標題。
Slug是 URL 路徑,例如巢狀頁面可設為guides/install。若未設定,系統會根據標題自動產生 slug。Description是頁面描述。
若要使用其他屬性名稱,請設定 dynamicSource() 的 properties 選項。
將整合權杖與資料庫的資料來源 ID 加入您的環境變數:
NOTION_TOKEN=ntn_...
# 注意:並非資料庫 URL 中的資料庫 ID
NOTION_DATA_SOURCE_ID=...內容來源
建立來源,並透過 getSource() 取得它的載入器:
import { Client } from '@notionhq/client';
import { dynamicLoader } from 'fumadocs-core/source';
import { createNotion } from '@fumadocs/notion/source';
export const notion = createNotion({
client: new Client({ auth: process.env.NOTION_TOKEN }),
dataSourceId: process.env.NOTION_DATA_SOURCE_ID!,
});
const source = dynamicLoader(
notion.dynamicSource({
// 只發佈已勾選 `Published` 的資料列
query: {
filter: { property: 'Published', checkbox: { equals: true } },
},
}),
{ baseUrl: '/docs' },
);
export async function getSource() {
return source.get();
}算繪頁面
page.data.load() 會擷取頁面的區塊,接著使用 NotionRenderer 算繪這些區塊:
import { getSource } from '@/lib/source';
import { DocsLayout } from 'fumadocs-ui/layouts/docs';
export default async function Layout({ children }: LayoutProps<'/docs'>) {
const source = await getSource();
return <DocsLayout tree={source.getPageTree()}>{children}</DocsLayout>;
}檔案路由
託管於 Notion 的檔案 (例如圖片和 PDF) 的 URL 大約一小時後就會失效。createNotionFileUrlResolver() 會將這些 URL 指向一個路由,再由該路由重新導向至新的 URL:
import { createNotionFileHandler } from '@fumadocs/notion';
import { notion } from '@/lib/source';
export const GET = createNotionFileHandler(notion);若要將路由掛載至其他路徑,請將同一個路徑傳給 resolver:
createNotionFileUrlResolver({ pageId: page.data.id, path: '/notion/file' });重新驗證
載入器會將頁面保留在記憶體中。在 Notion 中編輯內容後,請重新驗證載入器,例如透過 webhook 觸發:
export function revalidateNotion() {
return source.revalidate();
}若要在每次請求時都取得最新內容 (例如用於預覽) ,請在讀取前先將快取失效:
export async function getSource() {
source.invalidate();
return source.get();
}自訂區塊
傳入 components 即可覆寫特定區塊類型的算繪方式:
<NotionRenderer
blocks={blocks}
components={{
callout({ block, children, renderRichText }) {
return (
<aside className="rounded-lg bg-fd-muted p-4">
{renderRichText(block.callout.rich_text)}
{children}
</aside>
);
},
}}
// 預設使用 Shiki,設為 `false` 則輸出純文字程式碼,或傳入 `(code, language) => ReactNode`
highlightCode={false}
/>限制
- 指向子頁面及其他 Notion 頁面的連結會導向 Notion,因為只有資料庫中的資料列會成為您網站上的頁面。
- 檔案路由需要伺服器。若採用靜態匯出,請將檔案託管在 Notion 以外的地方,並省略
getFileUrl。
How is this guide?
最後更新於
