Mastodon powered comment section: a live experiment

This post refers to a live experiment. This post may update a few times. The code I discuss will start live but it may already be removed and/or destroyed by the time you read this.

I read a blog post titled “Adding comments to your static blog with Mastodon” and it sounded like quite a fun idea. I liked the idea that it means I can have comments on my site without writing a backend (this blog is a statically generated site). I could probably build a similar thing with a twitter api or some other service but what I liked about mastodon was the federation. With the way mastodon works the replies to my post (called a toot apparently) can come from any service that’s part of the fediverse.

The fediverse is effectively a set of different social networks that can communicate with each other. This means I’m not requiring people to make the same choice as me. As long as they have an account on a fediverse service they can join the conversation.

On with the experiment

The basic idea is that on my mastodon account I publish a toot (I’m not sure about this weird name). Then the replies to this toot become the comments of my blog.

Mastodon has an API for fetching the replies to a toot. So I can call my mastodon server’s API and fetch all the replies with a block of code like this:

function loadComments(host, postId) {
    const commentSection = document.getElementById('mastodon-comments');
    const purifySettings = { ALLOWED_TAGS: ['b', 'p', 'a'] };
        .then((response) => response.json())
        .then((data) => {
            if(data['descendants'] && Array.isArray(data['descendants']) && data['descendants'].length > 0) {
                data['descendants'].forEach(function(comment) {
                    const contentText = DOMPurify.sanitize(comment.content, purifySettings);
                    const contentSection = `<div class="comment-content">${contentText}</div>`;
                    const author = comment.account;
                    const authorSection = `<a class="comment-author" href="${author.url}"><img src="${author.avatar_static}" alt="${author.username} avatar">${author.display_name}</a>`;
                    commentSection.innerHTML += `<div class="mastodon-comment">${authorSection}${contentSection}</div>`;
            } else {
                commentSection.innerHTML += "<p><i class=\"fas fa-user-clock\"></i>No comments yet...</p>";

Try out the discussion

Hopefully if I’ve still got this code deployed you should see a comment section below this paragraph. With a link to take you to a page to join in the conversation.

Comments (from mastodon)