Build a Comment System for a Static Site with IndieAuth

Visitors sign in with IndieAuth, a Netlify Function accepts the comment, and the comment is saved as a file in the site's git repository. Covers the CORS, template and date-formatting problems I hit.

By
Brennan Kenneth Brown
Published
Reading time
4 minutes
Level
Advanced
You need
  • A static site on Netlify
  • Familiarity with serverless functions
Coffee mug reading 'Comments have been disabled' beside a keyboard
Comments are certainly not disabled on this post, or any other post for that matter! Source

To add comments to a static site with IndieAuth, visitors sign in with their own domain, a Netlify Function verifies them and accepts the comment, and the function commits the comment to your git repository as data. Third-party comment widgets hand conversations and user data to someone else; this approach keeps them in your repo with no tracking, no ads and minimal JavaScript. This guide shows how I built it with Eleventy, Netlify Functions, GitLab and IndieAuth, and the pitfalls I hit along the way.

What does the finished comment system do?

  • Stores comments in my GitLab repository in a data file.
  • Authenticates users through their own websites (IndieAuth).
  • Uses a comment form, serverless functions for authentication and storage, and a lightweight frontend.

How does IndieAuth sign-in work?

IndieAuth is a way to sign in to websites using your own domain name. If you have a website, you can use it to log in anywhere that supports IndieAuth, no need for yet another username and password.

To set this up, you need to add two links to your site's <head>:

<link rel="authorization_endpoint" href="https://indieauth.com/auth">
<link rel="token_endpoint" href="https://tokens.indieauth.com/token">

These tell IndieAuth providers where to send authentication requests and where to exchange authorization codes for access tokens. I'm implementing OAuth 2.0 with PKCE (Proof Key for Code Exchange) for security.

Step 1: How do I build the sign-in form?

The comment form starts simple, just asking for the user's website:

<form id="indieauth-form" action="https://indieauth.com/auth" method="get">
  <input id="me" type="url" name="me" placeholder="https://yourdomain.com" required />
  <!-- Hidden fields for OAuth -->
  <input type="hidden" name="client_id" value="{{ site.url }}" />
  <input type="hidden" name="redirect_uri" value="{{ site.url }}/auth/callback" />
  <input type="hidden" name="state" id="auth-state" />
  <input type="hidden" name="code_challenge" id="auth-code-challenge" />
  <input type="hidden" name="code_challenge_method" value="S256" />
</form>

Step 2: How do I add PKCE?

PKCE prevents someone from intercepting your authorization code. We generate a random "code verifier" and create a "code challenge" from it:

async function generatePKCE() {
  const verifier = generateRandomString(128);
  const challenge = await sha256(verifier);
  
  sessionStorage.setItem('pkce_verifier', verifier);
  
  return {
    verifier: verifier,
    challenge: challenge
  };
}

Step 3: How do I handle the callback?

After the user authenticates, IndieAuth redirects them back to our site with an authorization code. We handle this in a Netlify function that:

  • Verifies the state parameter matches what we sent
  • Exchanges the code for an access token
  • Passes the token back to our main page

Pitfall: How do I fix the IndieAuth CORS error?

When I first tried to exchange the authorization code from the frontend, I hit this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://tokens.indieauth.com/token

Browsers won't let you make requests to other domains from your JavaScript unless that domain explicitly allows it. And IndieAuth's token endpoint doesn't include the necessary CORS (Cross-Origin Resource Sharing) headers.

The solution is a server-side proxy. I created a Netlify function that handles the token exchange for us:

// netlify/functions/token-exchange.js
exports.handler = async (event, context) => {
  const response = await fetch('https://tokens.indieauth.com/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json'
    },
    body: querystring.stringify({
      grant_type: 'authorization_code',
      code: body.code,
      client_id: body.client_id,
      redirect_uri: body.redirect_uri,
      code_verifier: body.code_verifier
    })
  });
  
  // Return the response with proper CORS headers
  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(await response.json())
  };
};

How do I store comments in git?

Storing comments in the git repository means:

  • Comments are version controlled
  • They survive site rebuilds
  • You can edit them manually if needed
  • They are backed up with the site code

What does the comment function do?

The comment API function does a few things:

  1. Verifies the access token with IndieAuth
  2. Fetches existing comments from GitLab
  3. Adds the new comment
  4. Commits everything back to the repository

Here's the core logic:

// Fetch existing comments
async function fetchComments() {
  const response = await fetch(
    `https://gitlab.com/api/v4/projects/${projectId}/repository/files/src%2F_data%2Fcomments.js/raw?ref=main`,
    { headers: { 'Private-Token': gitlabToken } }
  );
  
  const content = await response.text();
  const match = content.match(/module\.exports = ({[\s\S]*});/);
  return JSON.parse(match[1]);
}

// Save comments back to GitLab
async function saveComments(comments) {
  const fileContent = `module.exports = ${JSON.stringify(comments, null, 2)};`;
  
  await fetch(`https://gitlab.com/api/v4/projects/${projectId}/repository/commits`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Private-Token': gitlabToken
    },
    body: JSON.stringify({
      branch: 'main',
      commit_message: `Update comments - ${new Date().toISOString()}`,
      actions: [{
        action: 'update',
        file_path: 'src/_data/comments.js',
        content: fileContent
      }]
    })
  });
}

Why doesn't a new comment appear immediately?

The site is static, so it has to rebuild before the comment shows. To handle this:

  1. Show a success message explaining what's happening
  2. Wait a few seconds for the build to start
  3. Refresh the page to show the new comment
showStatus('Comment posted successfully! The site is rebuilding now. Your comment will appear in a moment. This page will refresh automatically...', 'success');

setTimeout(() => {
  showStatus('Refreshing page to show your comment...', 'info');
  setTimeout(() => {
    window.location.reload();
  }, 2000);
}, 3000);

Pitfall: Why does getenv() fail in a Nunjucks template?

I tried to use getenv() in my Nunjucks template to check for development mode:

{% if getenv("NETLIFY_DEV") == "true" %}<!-- do something different for dev -->
{% endif %}

This results in a build error because Nunjucks doesn't have a getenv() function by default. The fix was to handle environment-specific logic in JavaScript instead of the template.

Pitfall: How do I format ISO date strings in readableDate?

Comments are saved with new Date().toISOString() which gives us a string like "2026-01-07T16:57:00.000Z". But the readableDate filter expected a JavaScript Date object.

The fix is to update the filter to handle both:

eleventyConfig.addFilter("readableDate", (dateObj) => {
  if (typeof dateObj === 'string') {
    return DateTime.fromISO(dateObj, { zone: "America/Edmonton" }).toFormat("MMMM d, yyyy 'at' h:mm a");
  }
  return DateTime.fromJSDate(dateObj, { zone: "America/Edmonton" }).toFormat("MMMM d, yyyy 'at' h:mm a");
});

All the code for this comment system is in my GitLab repository. Possible additions include edit and delete, notifications, avatar fetching and anti-spam measures.

How do I add reply threading?

Reply threading needs a change in each layer:

Data: Comments stay in a flat array. Replies just add a replyTo field pointing to the parent's id:

{
  "id": "abc123",
  "author": { "url": "https://example.com", "name": "Someone" },
  "content": "Great post!",
  "published": "2026-05-01T12:00:00.000Z",
  "replyTo": "parentCommentId"
}

Netlify function: Validates the parent exists, then conditionally includes replyTo on the new comment:

const { content, postUrl, replyTo } = requestBody;

if (replyTo) {
  const existingComments = comments[postUrl] || [];
  const parentExists = existingComments.some(c => c.id === replyTo);
  if (!parentExists) {
    return { statusCode: 400, body: JSON.stringify({ error: 'Parent comment not found' }) };
  }
}

const newComment = {
  id: crypto.randomBytes(16).toString('hex'),
  author: { ... },
  content: content,
  published: new Date().toISOString(),
  ...(replyTo ? { replyTo } : {})
};

Template: Two passes over the same flat array — root comments first, then their replies nested inside:

{% for comment in postComments %}
{% if not comment.replyTo %}
<article class="comment" id="comment-{{ comment.id }}">
  ...
  <div class="comment-replies">
    {% for reply in postComments %}
    {% if reply.replyTo == comment.id %}
    <article class="comment comment-reply">...</article>
    {% endif %}
    {% endfor %}
  </div>
</article>
{% endif %}
{% endfor %}

Frontend: The reply form POSTs to the same endpoint with the replyTo id in the body:

body: JSON.stringify({
  content: content,
  postUrl: postUrl,
  replyTo: replyToId
})

How can visitors sign in with their own site?

Visitors need IndieAuth set up on their own site:

  1. Add the endpoint links. Put the authorization and token endpoint links in the site's <head> (as shown above), then add a rel="me" link to a profile that links back to the site. Options include:
    • GitHub: <link rel="me" href="https://github.com/yourusername">
    • Email: <link rel="me" href="mailto:you@example.com">
    • Twitter: <link rel="me" href="https://twitter.com/yourusername">
    • Services like omg.lol have this pre-configured.
  2. Enter the site URL. In the comment form, enter the full website URL (for example https://yoursite.com) and click "Sign In".
  3. Authenticate on your own domain. The visitor is redirected to authenticate using their own website, with no third-party account needed.

Once authenticated, comments are verified as coming from that domain. To learn more about the IndieWeb, start with the IndieWeb wiki, or get a site on omg.lol, NeoCities or my 11ty IndieWeb starter. For related features, see Add Webmentions to an Eleventy Site and Publish to a Static Site with Micropub and Quill.

Resources