Skip to content

Adding Twikoo comment system to Astro

Updated: at 12:43

I am using CloudFlare’s CDN service - The integrity will change every version.

Create Comment.astro under src/components with below:

<div id="tcomment"></div>

// or `<script data-cfasync="false">` if you are on Cloudflare
  document.addEventListener("astro:page-load", () => {
    function loadTwikoo() {
      const commentsContainer = document.getElementById("tcomment");
      if (commentsContainer) {
        const script = document.createElement("script");
        script.src =
        script.defer = true;
        script.integrity =
        script.crossOrigin = "anonymous";
        script.referrerPolicy = "no-referrer";

        script.onload = () => {
          const initScript = document.createElement("script");
          initScript.innerHTML = `
              envId: "",
              el: "#tcomment",
              lang: "en-GB",

Place below in the page that you want to show the comment section.

import Comment from "~/components/Comment.astro";

<!-- The comment section -->
<Comment />

Source: Astro 添加 Twikoo 评论 by 老麦

Outdated - not automatically loaded since Astro v3

Twikoo is a comment system that can be easily deployed to cloud platforms with minimal work. I particularly like that it just blends into pages with zero styling!

Also, it has all features I am want for a comment system - e.g. emoji, admin, spam filtering, image upload, markdown, Katex, syntax highlighting and more - so no complaint at all.


Follow the quick start guide to deploy Twikoo backend.

Installing Twikoo package into the project

Install Twikoo with your package management. I am using pnpm.

pnpm install twikoo

Adding frontend JS to Astro

Add below code to the bottom of pages you want to show.

  import twikoo from "twikoo";
    envId: "https://YOUR_TWIKOO_URL", // your environment ID or url
    el: "#tcomment", // the container ID which will show the comment
    lang: "en-GB", // language for the comment template. for the full list, refer to
  }).then(() => {
    console.log("comment loading success");

For example, I want to show comments on each post and about page. The layout is defined in /src/layouts/PostDetails.astro and /src/layouts/AboutLayout.astro.

Declaring Twikoo module

The Twikoo package doesn’t have any type declared; so it will show as error in development.

Declare the module in main .d.ts file (in my case env.d.ts) to remove errors.

// Remove twikoo import error
declare module "twikoo";

Adding the comment container placeholder

Place below code. The code should be on the same page.

<div id="tcomment"></div>
<!-- the attribute of this element to correlates to `el` in the JS  -->

Viola. Job done! 👏👏👏

Leave a comment 💬