惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threat Research - Cisco Blogs
G
GRAHAM CLULEY
P
Privacy & Cybersecurity Law Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
P
Palo Alto Networks Blog
C
Cisco Blogs
AWS News Blog
AWS News Blog
T
Threatpost
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
Scott Helme
Scott Helme
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tor Project blog
Cyberwarzone
Cyberwarzone
P
Proofpoint News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
The Exploit Database - CXSecurity.com
The Register - Security
The Register - Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
罗磊的独立博客
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
N
News | PayPal Newsroom
Project Zero
Project Zero
NISL@THU
NISL@THU
博客园_首页
MyScale Blog
MyScale Blog
V2EX - 技术
V2EX - 技术
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
F
Full Disclosure
T
Troy Hunt's Blog
Recorded Future
Recorded Future
N
Netflix TechBlog - Medium
P
Privacy International News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
Arctic Wolf
C
Check Point Blog
W
WeLiveSecurity
Apple Machine Learning Research
Apple Machine Learning Research
C
CERT Recently Published Vulnerability Notes

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Adding comments to a static Astro blog with Netlify Forms
Roger Rajara · 2026-05-27 · via DEV Community

Original post: Adding comments to a static Astro blog with Netlify Forms

Series: Part of How this blog was built — documenting every decision that shaped this site.

Comments on a static site are one of those problems that sounds simple until you
actually sit down to solve it. You've got a few options.

You can reach for a third-party widget: Disqus, Commento, or Giscus. They all work,
and Giscus in particular is clever if your readers are likely to have GitHub
accounts. But they all introduce an external dependency you don't control, and
most of them inject JavaScript you didn't write.

You can build a full backend: a database, an API, authentication for moderation.
That's a lot of infrastructure for what is, on a personal blog, a fairly low-volume
use case.

Or you can use what you already have. If you're hosting on Netlify, you've already
got Netlify Forms and serverless
Functions available. The approach I settled on uses both, inspired by
Phil Hawksworth's jamstack-comments-engine.

The approach

The system runs in four steps:

  1. A visitor submits the comment form. Netlify intercepts the POST and stores it in its Forms queue. No backend code needed.
  2. A webhook triggers comment-handler, which sends an email with HMAC-signed approve and delete links.
  3. Clicking Approve calls approve-comment, which re-posts the comment data to a second form (approved-comments) and removes it from the queue.
  4. get-comments reads only from approved-comments, so only reviewed content ever reaches readers.

Mermaid diagram

Diagram fallback for Dev.to. View the canonical article for the full version: https://sourcier.uk/blog/comments-netlify-forms-astro

There's no database to provision, no moderation dashboard to watch, and no
third-party script on the page. Comments don't go live until I explicitly approve
them from my inbox.

The form

Netlify detects forms at build time by scanning the static HTML for data-netlify="true".
Because this is an Astro site, the form is a server-rendered .astro component, which
means it appears in the built HTML and Netlify registers it automatically on first deploy.

<form
  name="blog-comments"
  method="POST"
  data-netlify="true"
  netlify-honeypot="bot-field"
>
  <input type="hidden" name="form-name" value="blog-comments" />
  <input type="hidden" name="postSlug" value={postId} />
  <!-- honeypot -->
  <input name="bot-field" style="display:none" tabindex="-1" />
  <!-- fields: name, email (optional), comment -->
</form>

Enter fullscreen mode Exit fullscreen mode

A few things worth noting here:

  • The form-name hidden field is required when submitting via fetch rather than a native form POST. Netlify uses it to route the payload to the right form bucket.
  • postSlug stores the post identifier. When reading comments back, this is what ties each submission to its post.
  • The netlify-honeypot="bot-field" attribute tells Netlify to silently drop any submission that fills in the bot-field input. Real users don't see it; bots typically fill every field.

The form submits via fetch with Content-Type: application/x-www-form-urlencoded
to the current page URL; Netlify intercepts those requests before they hit the origin.

The functions

There are three Netlify Functions in total.

get-comments

netlify/functions/get-comments.js takes a ?slug= query param and fetches
submissions from the approved-comments form via the Netlify API, filtered by slug.

Email addresses are hashed server-side before the response leaves the function; the
raw address is never sent to the browser:

import crypto from "node:crypto";

function gravatarHash(email) {
  return crypto.createHash("md5").update(email.trim().toLowerCase()).digest("hex");
}

const comments = submissions
  .filter((s) => s.data?.postSlug === slug)
  .map((s) => ({
    name: s.data.name,
    comment: s.data.comment,
    // Use the original submission date, not the approval date
    date: s.data.originalDate || s.created_at,
    emailHash: s.data.email ? gravatarHash(s.data.email) : null,
  }))
  .sort((a, b) => new Date(a.date) - new Date(b.date));

Enter fullscreen mode Exit fullscreen mode

MD5 is the hash format Gravatar's API requires; hashing also means the raw email
address never leaves the server.

Using originalDate rather than created_at matters here: created_at on an
approved submission reflects the moment it was approved, not when the visitor
wrote it. The approval function stamps the original queue date into originalDate
when it copies the submission across.

The access token lives in an environment variable; it never touches the browser.
The function returns an empty array if the variables aren't set, so the site
degrades gracefully in local dev.

comment-handler

netlify/functions/comment-handler.js is triggered by a Netlify outgoing webhook
whenever a new submission hits the blog-comments queue. It sends an HTML email
via Resend (the same delivery layer used for new post notifications) containing the comment text and two
HMAC-SHA256-signed action links:

import crypto from "node:crypto";

function hmac(submissionId, action, secret) {
  return crypto
    .createHmac("sha256", secret)
    .update(`${submissionId}:${action}`)
    .digest("hex");
}

const approveToken = hmac(id, "approve", secret);
const deleteToken  = hmac(id, "delete",  secret);

const approveUrl =
  `${siteUrl}/.netlify/functions/approve-comment` +
  `?action=approve&id=${id}&token=${approveToken}`;

Enter fullscreen mode Exit fullscreen mode

Each token encodes both the submission ID and the intended action, so an approve
token can't be replayed as a delete, and tokens for one submission don't work on
another.

approve-comment

netlify/functions/approve-comment.js handles the link clicks. It:

  1. Verifies the HMAC token with crypto.timingSafeEqual to prevent timing attacks
  2. For approve: fetches the submission from the Netlify API, re-posts it to approved-comments with an originalDate field, then deletes the pending entry
  3. For delete: deletes the pending submission directly
  4. Returns a minimal HTML confirmation page either way
function verifyToken(submissionId, action, token, secret) {
  const expected = hmac(submissionId, action, secret);
  if (token.length !== expected.length) return false;
  return crypto.timingSafeEqual(
    Buffer.from(token, "hex"),
    Buffer.from(expected, "hex")
  );
}

Enter fullscreen mode Exit fullscreen mode

The approve step posts to the site's own URL; Netlify's edge intercepts it and
stores it in the approved-comments bucket, exactly as it does for visitor
submissions. No direct Netlify API write is needed.

Rendering comments

Client-side JavaScript calls /.netlify/functions/get-comments?slug={postId} on page
load and renders whatever comes back.

One discipline worth keeping here: never use innerHTML with raw user data. Because
the comment cards are built as an HTML template string, innerHTML is unavoidable for
inserting the full card structure, but all user-supplied values are passed through
escapeHtml before they touch the template:

function escapeHtml(str) {
  return String(str)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

Enter fullscreen mode Exit fullscreen mode

No raw user content ever reaches the HTML parser.

Gravatar avatars

Each commenter gets an avatar. If they provided an email address, the emailHash from
the function is used to fetch their Gravatar. If they didn't, or if no Gravatar is
registered, a pink circle with their initial is shown instead.

The d=404 parameter tells Gravatar to return a 404 rather than a default image.
onerror hides the <img> and the initial shows through. onload hides the initial
when a real Gravatar loads successfully:

const avatarInner = c.emailHash
  ? `<img src="https://www.gravatar.com/avatar/${c.emailHash}?s=72&d=404"
         onload="this.nextElementSibling.style.display='none'"
         onerror="this.style.display='none'" />
     <span class="comment__avatar-initial">${initial}</span>`
  : `<span class="comment__avatar-initial">${initial}</span>`;

Enter fullscreen mode Exit fullscreen mode

The <span> is always in the DOM behind the image, so the fallback requires no extra
logic.

Styling dynamically injected content in Astro

This tripped me up. Astro's scoped CSS works by adding a unique attribute
(e.g. data-astro-cid-xxx) to every element it renders, and then qualifying all the
CSS selectors with that attribute. That means the styles only match elements that were
rendered at build time.

Comment cards are injected via innerHTML at runtime; they never get the scoping
attribute. The fix is to wrap those selectors in :global():

/* scoped — applies to server-rendered elements */
.comments__heading { ... }

/* global — applies to runtime-injected elements */
:global(.comment) { ... }
:global(.comment__avatar) { ... }

Enter fullscreen mode Exit fullscreen mode

Everything that's server-rendered stays scoped. Only the comment card classes need to
escape scoping.

Registering the approved-comments form

Netlify discovers forms by scanning built HTML at deploy time. The blog-comments
form lives in the Comments.astro component, so it's found automatically. The
approved-comments form is never rendered on a page; it only receives programmatic
POSTs from approve-comment. Without an explicit registration it would never be
created in the Netlify dashboard.

The fix is a hidden placeholder form in Comments.astro, alongside the visible
blog-comments form that visitors submit:

<form name="approved-comments" data-netlify="true" hidden aria-hidden="true">
  <input type="hidden" name="postSlug" />
  <input type="hidden" name="name" />
  <input type="hidden" name="email" />
  <input type="hidden" name="comment" />
  <input type="hidden" name="originalDate" />
</form>

Enter fullscreen mode Exit fullscreen mode

Netlify only needs to find a form in one built page to register it. Since
Comments.astro is rendered on every blog post, the form is present in every post
page's HTML and will be picked up on the first deploy. The hidden attribute keeps
it invisible; aria-hidden="true" removes it from the accessibility tree.

Setting it up on Netlify

After the first deploy:

  1. Get a personal access token: Netlify → User settings → Applications → Personal access tokens
  2. Set up a Resend account and verify a sender domain (their free tier covers 3,000 emails per month, more than enough). If you already followed the mailing list post, your Resend account and sender domain are already configured.
  3. Add these environment variables in Netlify → Site configuration → Environment variables:
    • NETLIFY_PAT: personal access token from step 1. Avoid the name NETLIFY_ACCESS_TOKEN; Netlify auto-overwrites it at runtime with a limited machine token
    • APPROVAL_SECRET: a random secret for HMAC signing (openssl rand -hex 32 works well)
    • SITE_URL: the public URL, e.g. https://sourcier.uk
    • RESEND_API_KEY: Resend API key
    • NOTIFY_FROM_EMAIL: verified Resend sender address
    • NOTIFY_EMAIL: where to receive approval emails
  4. Add a webhook: Netlify → Forms → blog-comments → Form notifications → Add notification → Outgoing webhook → URL: https://your-site/.netlify/functions/comment-handler
  5. Submit a test comment to create the first approved-comments entry, then copy its Form ID from the Netlify Forms dashboard URL
  6. Add the final variable:
    • APPROVED_COMMENTS_FORM_ID: form ID from step 5
  7. Trigger a redeploy

After that, every new comment fires a notification email. Approve or delete it
by clicking the link. No dashboard visit required.

Refreshing the list after submission

After a successful POST, loadComments() is called a second time so the list
reflects whatever the server currently holds. Because Netlify Forms requires manual
approval before submissions appear via the API, the newly posted comment won't show
up immediately, but any comments approved in the meantime will, and the list stays
in sync rather than going stale.

To make the refresh feel intentional rather than jarring, renderComments accepts
an animate flag. When set, the list container fades out, swaps its HTML, then
fades back in:

function renderComments(comments, animate = false) {
  const html = buildCommentsHtml(comments);
  if (!animate) {
    listEl.innerHTML = html;
    return;
  }
  listEl.classList.add("is-fading");
  listEl.addEventListener("animationend", () => {
    listEl.innerHTML = html;
    listEl.classList.remove("is-fading");
    listEl.classList.add("is-entering");
    listEl.addEventListener(
      "animationend",
      () => listEl.classList.remove("is-entering"),
      { once: true },
    );
  }, { once: true });
}

Enter fullscreen mode Exit fullscreen mode

The initial page-load call passes no flag, so the first render is instant with no
flash. The post-submission refresh passes animate = true.

The two CSS keyframes are defined in the component's scoped styles:

@keyframes comments-fade-out {
  from { opacity: 1; transform: translateY(0); }
  to   { opacity: 0; transform: translateY(-6px); }
}

@keyframes comments-fade-in {
  from { opacity: 0; transform: translateY(8px); }
  to   { opacity: 1; transform: translateY(0); }
}

:global(#comments-list.is-fading)  { animation: comments-fade-out 0.2s ease forwards; }
:global(#comments-list.is-entering) { animation: comments-fade-in  0.25s ease forwards; }

Enter fullscreen mode Exit fullscreen mode

The selectors need :global() for the same reason comment card styles do; the list
element is in the server-rendered HTML but the classes are toggled at runtime by
JavaScript, so Astro's scoped-CSS attribute won't be present on the selector when the
animation fires.

What I'd do differently

The main remaining limitation is that comments don't appear immediately after
submission; the visitor sees a "submitted for review" message and has to come
back later to see it live. The list refreshes after submission, but an unapproved
comment can't show up in that refresh.

The cleanest fix would be to optimistically insert the pending comment into the
DOM immediately, marked visually as "awaiting approval", and then confirm or
remove it on the next real fetch. That adds state management I haven't needed
yet; volume is low enough that the current UX is fine for now.

Wrap-up

The full implementation spans four files: Comments.astro and the three serverless
functions. Netlify Forms handles the queue and webhook delivery, Resend sends the
notification email, and the HMAC signing keeps approve and delete actions
tamper-proof. Nothing goes live until I've clicked a link from my inbox, with no
database to provision and no third-party script on the page.

The Comments.astro component and all three functions are in the
sourcier.uk repository if you want to
use them as a starting point.