FastComments.com

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

本指南說明如何將 FastComments 即時留言小工具加入到以 Strapi 管理內容的網站。Strapi 是一個無頭(headless)CMS,不會渲染頁面,因此小工具需加入到渲染 Strapi 內容條目的前端應用程式中。每個留言串以條目的 documentId 識別,因此即使條目的 slug 或 URL 變更,留言串仍會與該條目保持關聯。

Strapi 本身並未提供供網站訪客使用的留言系統。Strapi Marketplace 上有列出相關的第三方外掛,例如 Comments(strapi-plugin-comments,由 Sensinum 維護),它會將留言以內容類型的形式儲存在 Strapi 資料庫中。FastComments 則是將留言儲存在 FastComments 的伺服器上,且不需要安裝任何 Strapi 外掛。

本教學需要一個 FastComments 帳號。你可以在此建立帳號。

步驟 1:取得條目的 documentId Internal Link

在 Strapi 5 中,一個文件會將每個語系條目的草稿與已發布版本分組在一起,而 REST API 透過 documentId 來識別文件。使用 documentId 作為 FastComments 的討論串 ID,可以在條目的 slug、標題或 URL 變更時,讓留言仍然附著在該條目上。

前端通常會透過 slug 來載入條目。本指南中的範例使用一個複數 API ID 為 articles 的集合類型,以及一個 slug 欄位。請將它們替換為您自己的內容類型與欄位名稱。

透過 Slug 尋找條目
Copy Copy
1
2GET /api/articles?filters[slug][$eq]=hello-world
3

回應會在 data 陣列中包含符合的條目。每個條目都包含其 documentId:

回應
Copy Copy
1
2{
3 "data": [
4 {
5 "id": 12,
6 "documentId": "znrlzntu9ei5onjvwfaalu2v",
7 "title": "Hello World",
8 "slug": "hello-world"
9 }
10 ],
11 "meta": {
12 "pagination": { "page": 1, "pageSize": 25, "pageCount": 1, "total": 1 }
13 }
14}
15

請使用 data[0].documentId 作為討論串 ID。請勿使用數字的 id:在 Strapi 5 中,同一文件的不同語系之間該值會有所不同。

存取 REST API

內容類型預設為私有。若要允許前端讀取條目,請執行以下其中一項操作:

  • 在管理面板中,開啟 Users & Permissions 外掛 > Roles,編輯 Public 角色,為該內容類型啟用 find 操作,然後點擊 Save。
  • 在 Settings > Global settings > API Tokens 中建立一個 Read-only 權杖,並在 Authorization: Bearer <token> 標頭中傳送。請僅從伺服器端程式碼傳送該權杖,以避免暴露給瀏覽器。

已發布內容與語系

除非請求設定 status=draft,否則 REST API 會回傳文件的已發布版本。草稿與已發布版本的 documentId 是相同的。

文件的所有語系共用同一個 documentId,因此條目的每個語系都會顯示相同的留言討論串。若要為每個語系保留獨立的討論串,請將兩個值組合起來,例如 documentId + '-' + locale。

Strapi 4

在 Strapi 4 中,REST API 的回應不包含 documentId。每個條目都有一個數字的 id,且其欄位巢狀於 attributes 之下。請使用 data[0].id 作為討論串 ID,並從 data[0].attributes 讀取欄位。

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

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

安裝 FastComments Next.js 函式庫
Copy Copy
1
2npm install fastcomments-nextjs
3

在文章頁面渲染小工具

此頁面是一個 Server Component。它透過 slug 從 Strapi 取得文章,並將文章的 documentId 作為 urlId 傳遞給留言小工具。建立 app/articles/[slug]/page.tsx:

app/articles/[slug]/page.tsx
Copy Copy
1
2import { notFound } from 'next/navigation';
3import { FastComments } from 'fastcomments-nextjs';
4
5async function getArticle(slug: string) {
6 const res = await fetch(
7 `${process.env.STRAPI_URL}/api/articles?filters[slug][$eq]=${encodeURIComponent(slug)}`,
8 { headers: { Authorization: `Bearer ${process.env.STRAPI_API_TOKEN}` } }
9 );
10 if (!res.ok) {
11 throw new Error(`Strapi request failed with status ${res.status}`);
12 }
13 const json = await res.json();
14 return json.data[0];
15}
16
17export default async function ArticlePage({ params }: { params: Promise<{ slug: string }> }) {
18 const { slug } = await params;
19 const article = await getArticle(slug);
20 if (!article) {
21 notFound();
22 }
23
24 return (
25 <article>
26 <h1>{article.title}</h1>
27 <FastComments
28 key={article.documentId}
29 tenantId="demo"
30 urlId={article.documentId}
31 url={`https://example.com/articles/${slug}`}
32 />
33 </article>
34 );
35}
36

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

在 Next.js 應用程式的環境中設定 STRAPI_URL 和 STRAPI_API_TOKEN,例如在 .env.local 中。如果 Public 角色具有 find 權限,請移除 headers 選項。將 https://example.com/articles/ 替換為您文章頁面的公開網址。

  • urlId 用於識別留言串。它被設定為文章的 documentId。
  • 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 腳本載入小工具。渲染條目的模板會將條目的 documentId 寫入 data-entry-id 屬性,腳本再將其以 urlId 傳遞給小工具:

Strapi FastComments 程式碼
Copy Copy
1
2<div id="fastcomments-widget" data-entry-id="ENTRY_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-entry-id'),
10 url: window.location.origin + window.location.pathname
11 });
12 })();
13</script>
14

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

請將 ENTRY_DOCUMENT_ID 替換為條目 documentId 的模板表達式。例如,在 Astro 元件中該屬性寫作 data-entry-id={article.documentId},而在 Vue 模板中則寫作 :data-entry-id="article.documentId"。

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

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

為每個條目啟用或停用留言 Internal Link

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

在 Content-Type Builder 中新增欄位

Content-Type Builder 僅在 Strapi 以開發模式執行時可用。

  1. 開啟 Content-Type Builder 並選擇集合類型,例如 Article。
  2. 點擊 Add another field 並選擇 Boolean。
  3. 輸入 commentsEnabled 作為名稱。在進階設定中,將預設值設為 true。
  4. 點擊 Finish,然後點擊 Save。

Content-Type Builder 會將該欄位寫入內容類型的 schema.json 檔案,例如 src/api/article/content-types/article/schema.json。該屬性也可以直接加入該檔案:

schema.json 屬性
Copy Copy
1
2"attributes": {
3 "commentsEnabled": {
4 "type": "boolean",
5 "default": true
6 }
7}
8

在前端檢查該欄位

REST API 會將該欄位與條目的其他欄位一併回傳。在步驟 2 的 Next.js 頁面中,僅在該欄位不為 false 時渲染 FastComments 元件:

條件渲染
Copy Copy
1
2{article.commentsEnabled !== false && (
3 <FastComments
4 key={article.documentId}
5 tenantId="demo"
6 urlId={article.documentId}
7 url={`https://example.com/articles/${slug}`}
8 />
9)}
10

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

此檢查使用 !== false,因此沒有該欄位值的條目(例如在新增該欄位之前建立的條目)仍會顯示留言。

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

自訂設定 Internal Link

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

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