FastComments.com

为 Strapi 网站添加实时评论功能

本指南将 FastComments 实时评论组件添加到一个内容由 Strapi 管理的网站。Strapi 是一个无头 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 中创建一个只读令牌,并通过 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/ 替换为您文章页面的公开 URL。

  • 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

内容类型上的一个布尔字段允许编辑者为单个条目关闭评论。前端读取该字段,仅在启用评论时渲染评论组件。

在内容类型构建器中添加字段

内容类型构建器仅在 Strapi 以开发模式运行时可用。

  1. 打开内容类型构建器并选择集合类型,例如 Article。
  2. 点击 Add another field 并选择 Boolean。
  3. 输入 commentsEnabled 作为名称。在高级设置中,将默认值设置为 true。
  4. 点击 Finish,然后点击 Save。

内容类型构建器会将该字段写入内容类型的 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 库时,配置选项作为 FastComments 组件的 props 传递。使用脚本嵌入时,它们被添加到传递给 window.FastCommentsUI 的对象中。