FastComments.com

Add Live Commenting to Sites Built with Contentful

This guide adds the FastComments live commenting widget to a website or app whose content is stored in Contentful.

Contentful is a headless CMS and does not render pages. The widget is added to the frontend that fetches entries from the Content Delivery API and renders them, and each comment thread is tied to the entry's ID rather than to its slug or URL. Contentful's own comments, in the Comments tab of the entry editor, are for members of the space to discuss an entry while editing it. They are not shown to visitors of the site.

This tutorial requires a FastComments account. You can create an account here.

Get the Entry ID Internal Link

Every Contentful entry has a unique ID in its sys.id property. Contentful's sys properties cannot be edited, so the ID stays the same when an editor changes the entry's slug, title, or any other field. Passing sys.id to FastComments as the urlId keeps the entry's comment thread attached to the entry when its slug or the URL structure of the site changes.

The examples in this guide use Contentful's JavaScript library, contentful, which runs in Node.js and in the browser:

Install the Contentful Library
Copy Copy
1
2npm install contentful
3

The following module creates a Content Delivery API client and looks up a blog post entry by its slug. It assumes a content type with the ID blogPost that has a slug field. The space ID and the Content Delivery API access token are read from environment variables.

lib/contentful.js
Copy Copy
1
2import * as contentful from 'contentful';
3
4const client = contentful.createClient({
5 space: process.env.CONTENTFUL_SPACE_ID,
6 accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
7});
8
9export async function getPostBySlug(slug) {
10 const entries = await client.getEntries({
11 content_type: 'blogPost',
12 'fields.slug': slug,
13 limit: 1,
14 });
15 return entries.items[0];
16}
17

getEntries returns a collection whose items array holds the matching entries. Each entry has a sys object, which contains the ID, and a fields object with the values of the content type's fields. For the entry returned above, the comment thread ID is entry.sys.id, for example 5PeGS2SoZGSa4GuiQsigQu.

Requirements of the Content Delivery API that apply to this query:

  • content_type is required whenever the query filters on fields.
  • The equality filter 'fields.slug': slug does not work on long text fields (API type Text). The slug field must be a short text field (API type Symbol).

Add the Widget in Next.js Internal Link

This example uses the Next.js App Router and the FastComments Next.js library, fastcomments-nextjs, which supports Next.js 13 to 16 with React 18 or 19.

Install the FastComments Next.js Library
Copy Copy
1
2npm install fastcomments-nextjs
3

The page below is a server component for the route /blog/[slug]. It fetches the entry with the getPostBySlug function from the previous step and renders the comment widget with the entry ID as the urlId:

app/blog/[slug]/page.js
Copy Copy
1
2import { notFound } from 'next/navigation';
3import { FastComments } from 'fastcomments-nextjs';
4import { getPostBySlug } from '@/lib/contentful';
5
6export default async function BlogPostPage({ params }) {
7 const { slug } = await params;
8 const post = await getPostBySlug(slug);
9
10 if (!post) {
11 notFound();
12 }
13
14 return (
15 <article>
16 <h1>{post.fields.title}</h1>
17 <FastComments
18 key={post.sys.id}
19 tenantId="demo"
20 urlId={post.sys.id}
21 />
22 </article>
23 );
24}
25

If you are logged in to FastComments, the snippet above contains your tenant ID. Otherwise, replace demo with your tenant ID.

Notes on the example:

  • The FastComments component declares 'use client' itself, so it can be rendered from a server component without a wrapper.
  • The Contentful client runs only on the server in this page, so the access token is not sent to the browser and the environment variables do not need the NEXT_PUBLIC_ prefix.
  • The key prop makes React mount a new widget when the reader navigates from one entry to another.
  • params is a promise in Next.js 15 and later. In Next.js 13 and 14 it is a plain object, and await on it returns the same object.
  • For accounts in the EU region, add region="eu" to the component.

The comment widget uses the current page URL as the link for notification emails and the moderation page. To link comments to a different URL, pass a url prop. See How Comments are Tied to Pages and Articles.

For React applications that do not use Next.js, the React library provides the FastCommentsCommentWidget component, which takes the same tenantId and urlId props.

Add the Widget Without a Framework Library Internal Link

Frontends that render HTML from a template, or that do not use a FastComments framework library, can load the widget with the FastComments VanillaJS script. The template writes the entry's sys.id into a data-entry-id attribute on the widget container, and the script passes it to the widget as the urlId.

Add the following to the template that renders an entry, at the position where the comments should appear. Replace ENTRY_ID with the template expression that outputs the entry's sys.id.

Contentful FastComments Code
Copy Copy
1
2<script src="https://cdn.fastcomments.com/js/embed-v2.min.js"></script>
3<div id="fastcomments-widget" data-entry-id="ENTRY_ID"></div>
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 });
11 })();
12</script>
13

If you are logged in to FastComments, the snippet above contains your tenant ID. Otherwise, replace demo with your tenant ID.

For accounts in the EU region, load the script from https://cdn-eu.fastcomments.com/js/embed-v2.min.js and add region: 'eu' to the configuration object.

In a single-page application that fetches entries in the browser with the contentful library, pass entry.sys.id to urlId directly instead of reading it from an attribute.

FastComments also has libraries for other frontend frameworks. Each of them accepts a urlId option that takes the entry ID in the same way:

Turn Comments On or Off per Entry Internal Link

To let editors turn comments on or off for individual entries, add a Boolean field to the content type and check it in the frontend before rendering the widget.

Add the Field to the Content Model

  1. In the Contentful web app, go to the Content model tab and open the content type, for example Blog Post.
  2. Click Add field and select Boolean.
  3. Enter Comments Enabled as the name and check that the field ID is commentsEnabled.
  4. Click Add and configure. Optionally, set a default value in the Default value tab. Contentful applies default values to entries when they are created.
  5. Click Confirm, then click Save to save the content type.

Check the Field in the Frontend

The following version of the Next.js page renders the widget unless the entry's commentsEnabled field is false. Entries that were created before the field existed, and have no value for it, show comments.

app/blog/[slug]/page.js
Copy Copy
1
2import { notFound } from 'next/navigation';
3import { FastComments } from 'fastcomments-nextjs';
4import { getPostBySlug } from '@/lib/contentful';
5
6export default async function BlogPostPage({ params }) {
7 const { slug } = await params;
8 const post = await getPostBySlug(slug);
9
10 if (!post) {
11 notFound();
12 }
13
14 const showComments = post.fields.commentsEnabled !== false;
15
16 return (
17 <article>
18 <h1>{post.fields.title}</h1>
19 {showComments && (
20 <FastComments
21 key={post.sys.id}
22 tenantId="demo"
23 urlId={post.sys.id}
24 />
25 )}
26 </article>
27 );
28}
29

If you are logged in to FastComments, the snippet above contains your tenant ID. Otherwise, replace demo with your tenant ID.

To show comments only on entries where an editor has set the field to true, use post.fields.commentsEnabled === true instead.

Hiding the widget does not delete the entry's comments. When the field is changed back, the existing thread is shown again because it is still stored under the entry ID.

To allow reading existing comments while preventing new ones, keep the widget and pass readonly={true} to the component instead of hiding it. See Prevent New Replies & Disable Votes.

Customization Internal Link

Styling and configuration options for the widget are described in the Customization Documentation.

With the Next.js library, configuration options are passed as props of the FastComments component. With the VanillaJS script, they are added to the object passed to window.FastCommentsUI. Many options can also be changed without code on the widget customization page of your FastComments account.

To show signed-in users of your site as the comment authors, use FastComments Secure SSO. The SSO verification hash is an HMAC-SHA256 hash computed with your FastComments API secret, so it must be generated in server-side code, such as a Next.js server component, and passed to the widget. Do not compute it in browser JavaScript or include the API secret in client-side code.