FastComments.com

為 Sanity 網站新增即時留言功能

本指南說明如何將 FastComments 即時留言小工具新增至以 Sanity 管理內容的網站。Sanity 負責儲存內容並透過其 API 提供內容,但不會渲染公開網站,因此小工具需新增至渲染 Sanity 文件的前端應用程式中。每個留言串皆以文件的 _id 識別,因此當文件的 slug 或 URL 變更時,留言串仍會與文件保持關聯。

Sanity 並未為網站訪客提供留言功能。Sanity Studio 內建 Comments 功能(適用於 Growth 方案),可讓 Studio 使用者在編輯內容時對欄位與文字留言。這些留言是供內容團隊使用,不會顯示在公開網站上。

本教學需要 FastComments 帳號。您可以在此建立帳號。

步驟 1:查詢文件的 _id Internal Link

每個 Sanity 文件都有一個 _id,且該 ID 在文件建立後無法修改。使用 _id 作為 FastComments 的討論串 ID,可以在文件的 slug、標題或 URL 變更時,讓留言持續附加在該文件上。

前端通常會透過 slug 載入文件。本指南中的範例使用名為 post 的文件類型,並帶有 slug 欄位。請將它們替換為您自己的文件類型與欄位名稱。

使用 @sanity/client 建立一個 client,例如在 sanity/client.ts 中。請將專案 ID 和 dataset 替換為您 Sanity 專案的值:

sanity/client.ts
Copy Copy
1
2import { createClient } from '@sanity/client';
3
4export const client = createClient({
5 projectId: 'your-project-id',
6 dataset: 'production',
7 useCdn: true,
8 apiVersion: '2025-02-19'
9});
10

透過 slug 查詢文件,並使用 GROQ 選取其 _id:

Fetch a Post by Slug
Copy Copy
1
2const post = await client.fetch(
3 '*[_type == "post" && slug.current == $slug][0]{_id, title}',
4 { slug: 'hello-world' }
5);
6// post._id is the thread ID, for example "ecfef291-60f0-4609-bbfc-263d11a48c43"
7

草稿與已發佈的 _id

Sanity 將未發佈的草稿儲存為獨立的文件,其 ID 為已發佈 ID 加上 drafts. 前綴,例如 drafts.ecfef291-60f0-4609-bbfc-263d11a48c43。已發佈文件的 _id 則沒有前綴。前端必須使用已發佈的 _id,這樣草稿頁面與已發佈頁面才會顯示相同的討論串。

  • 使用 API 版本 2025-02-19 及之後的版本時,查詢預設使用 published perspective,且僅回傳已發佈的文件,因此 _id 沒有前綴。
  • 使用 drafts perspective(用於預覽)時,_id 是已發佈的 ID,而草稿 ID 則位於 _originalId 中。
  • 使用 raw perspective(2025-02-19 之前 API 版本的預設值)時,經過身分驗證的查詢可能會在回傳已發佈文件的同時也回傳草稿文件。請在 createClient 中設定 perspective: 'published',或在將 _id 傳給 FastComments 之前移除 drafts. 前綴。

步驟 2:在 Next.js 中新增小工具 Internal Link

此步驟使用 Next.js App Router 以及 FastComments Next.js 函式庫 fastcomments-nextjs,該函式庫支援搭配 React 18 或 19 的 Next.js 13 至 16。在 Next.js 專案中安裝此函式庫與 Sanity 用戶端:

安裝套件
Copy Copy
1
2npm install fastcomments-nextjs @sanity/client
3

在文章頁面渲染小工具

該頁面是一個 Server Component。它透過 slug 從 Sanity 查詢文章,並將文章的 _id 作為 urlId 傳遞給留言小工具。使用步驟 1 的用戶端建立 app/posts/[slug]/page.tsx:

app/posts/[slug]/page.tsx
Copy Copy
1
2import { notFound } from 'next/navigation';
3import { FastComments } from 'fastcomments-nextjs';
4import { client } from '../../../sanity/client';
5
6const POST_QUERY = '*[_type == "post" && slug.current == $slug][0]{_id, title}';
7
8export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
9 const { slug } = await params;
10 const post = await client.fetch(POST_QUERY, { slug });
11 if (!post) {
12 notFound();
13 }
14
15 return (
16 <article>
17 <h1>{post.title}</h1>
18 <FastComments
19 key={post._id}
20 tenantId="demo"
21 urlId={post._id}
22 url={`https://example.com/posts/${slug}`}
23 />
24 </article>
25 );
26}
27

如果您已登入 FastComments,上述程式碼片段會包含您的租戶 ID。否則,請將 demo 替換為您的租戶 ID。

此範例從專案根目錄的 sanity/client.ts 匯入用戶端。請根據您的用戶端檔案位置調整匯入路徑。將 https://example.com/posts/ 替換為您文章頁面的公開網址。

  • urlId 用於識別留言串。它被設定為文章的 _id。
  • url 是頁面的連結,FastComments 會在通知中使用它。
  • key 讓 React 在讀者從一篇文章導覽到另一篇時掛載新的小工具。
  • FastComments 元件自行宣告了 'use client',因此可以直接從 Server Component 渲染,無需包裝器。

在 Next.js 14 及更早版本中,params 是一個普通物件而非 Promise,對它使用 await 會回傳相同的物件。

EU 帳戶

如果您的 FastComments 帳戶位於 EU 區域,請在 FastComments 元件中加入 region="eu"。

在不使用框架函式庫的情況下新增小工具 Internal Link

不使用 React 的前端,例如 Astro、Nuxt 或伺服器端渲染的模板,可以透過 FastComments 腳本載入小工具。渲染文章的模板會將文件的 _id 寫入 data-document-id 屬性,腳本再將其以 urlId 傳遞給小工具:

Sanity FastComments 程式碼
Copy Copy
1
2<div id="fastcomments-widget" data-document-id="SANITY_DOCUMENT_ID"></div>
3<script src="https://cdn.fastcomments.com/js/embed-v2.min.js"></script>
4<script>
5 (function () {
6 var container = document.getElementById('fastcomments-widget');
7 window.FastCommentsUI(container, {
8 tenantId: 'demo',
9 urlId: container.getAttribute('data-document-id'),
10 url: window.location.origin + window.location.pathname
11 });
12 })();
13</script>
14

如果您已登入 FastComments,上述程式碼片段已包含您的租戶 ID。否則,請將 demo 替換為您的租戶 ID。

請將 SANITY_DOCUMENT_ID 替換為模板中取得文件已發佈 _id 的表達式。例如,在 Astro 元件中該屬性寫作 data-document-id={post._id},而在 Vue 模板中寫作 :data-document-id="post._id"。

如果您的 FastComments 帳號位於 EU 區域,請從 https://cdn-eu.fastcomments.com/js/embed-v2.min.js 載入腳本,並在傳遞給 window.FastCommentsUI 的物件中加入 region: 'eu'。

FastComments 也為其他框架提供元件庫,包括 Astro、Vue 和 Svelte。使用這些元件庫時,請將 _id 作為留言小工具的 urlId 選項傳入。

為個別文件啟用或停用留言功能 Internal Link

文件類型上的布林值欄位可讓編輯者針對個別文件關閉留言功能。前端會讀取該欄位,並僅在留言功能啟用時渲染小工具。

將欄位加入 Schema

在您的 Studio 專案中,於文件類型的 schema 加入 commentsEnabled 欄位:

schemaTypes/post.ts
Copy Copy
1
2import { defineField, defineType } from 'sanity';
3
4export const post = defineType({
5 name: 'post',
6 title: 'Post',
7 type: 'document',
8 fields: [
9 // 現有欄位,例如 title 與 slug
10 defineField({
11 name: 'commentsEnabled',
12 title: 'Comments enabled',
13 type: 'boolean',
14 initialValue: true
15 })
16 ]
17});
18

initialValue 會將在加入該欄位後於 Studio 中建立的文件之欄位設為 true。現有文件在編輯者設定該欄位之前不會包含 commentsEnabled 鍵,而 GROQ 對於缺失的鍵會回傳 null。

在前端檢查該欄位

將該欄位加入 GROQ 投影:

GROQ Query
Copy Copy
1
2const POST_QUERY = '*[_type == "post" && slug.current == $slug][0]{_id, title, commentsEnabled}';
3

在步驟 2 的 Next.js 頁面中,僅在該欄位不為 false 時渲染 FastComments 元件:

Conditional Rendering
Copy Copy
1
2{post.commentsEnabled !== false && (
3 <FastComments
4 key={post._id}
5 tenantId="demo"
6 urlId={post._id}
7 url={`https://example.com/posts/${slug}`}
8 />
9)}
10

如果您已登入 FastComments,上述程式碼片段會包含您的租戶 ID。否則,請將 demo 替換為您的租戶 ID。

此檢查使用 !== false,因此沒有該欄位值的文件仍會顯示留言。若要改為在沒有該欄位值的文件上隱藏留言,請使用 post.commentsEnabled === true。

隱藏小工具並不會刪除文件既有的留言。當該欄位重新設為 true 時,留言會再次顯示。

自訂設定 Internal Link

小工具的樣式與設定選項在自訂化文件中有詳細說明。

使用 Next.js 函式庫時,設定選項會以 props 的形式傳遞給 FastComments 元件。使用腳本嵌入時,則是將設定選項加入傳遞給 window.FastCommentsUI 的物件中。