Skip to main content

Astro Integration

@respectify/astro adds a comment section to an Astro site, with every comment moderated by Respectify before it is stored. It gives you the <CommentSection> component, Astro Actions for submitting and deleting comments, an API route that lists them, and comment stores for Postgres and SQLite through your own Drizzle connection. Posts can stay prerendered; only the actions and the API route run on the server.

If you already have a comment system and only want the moderation call, use @respectify/astro-moderation (moderateComment(), no UI or database) or the TypeScript client directly. This page covers @respectify/astro.

Requirements​

  • Astro 5, 6 or 7 with output: 'server' (or hybrid) and a server adapter (Node, Vercel, Netlify, and so on)
  • A database reached through Drizzle ORM: Postgres (node-postgres, postgres.js, Neon, PGlite) or SQLite (libSQL/Turso, better-sqlite3, Cloudflare D1)
  • A Respectify account. A new account has 200 free comments and needs no card; the API key shown on your first dashboard visit is the one to use

Quick Setup​

From version 1.2.0 two commands do most of the setup. First add the integration, and a server adapter if your site has none:

npx astro add @respectify/astro
npx astro add node

Then let the package write its own files:

npx @respectify/astro init

init asks whether your comments go in Postgres or SQLite (or pass --database postgres or --database sqlite; a project that already has a drizzle.config is not asked) and writes:

FileWhat it is
src/respectify.runtime.tsThe runtime module: connects to your database and creates the comment store
respectify.config.jsonModeration settings, with the defaults
src/actions/index.tsAstro Actions exposing the comment actions
src/db/schema.tsA Drizzle schema with the comment table
drizzle.config.tsA drizzle-kit config for creating the table

A file that already exists is never overwritten. If you already use Drizzle, your drizzle.config is kept and the comment table is added as one line at the end of the schema file it names. Where init cannot safely make a change itself, such as a site that already has actions, it prints the lines for you to add.

It ends with a numbered list of what is left, with the exact commands for your package manager:

  1. Install the database packages it names (Drizzle and your database driver).
  2. Set RESPECTIFY_EMAIL, RESPECTIFY_API_KEY and DATABASE_URL in your environment. The API key is the one from your dashboard.
  3. Create the comment table with npx drizzle-kit generate and npx drizzle-kit migrate.
  4. Put <CommentSection postSlug={post.id} /> on a page, as shown in step 5 below.

The rest of this section describes the same setup done by hand, which is also what the generated files contain.

Manual Setup​

Install the package, the Respectify client, Drizzle and your database driver. For Postgres with node-postgres:

npm install @respectify/astro @respectify/client drizzle-orm pg
npm install -D drizzle-kit @types/pg

For libSQL/Turso install @libsql/client instead of pg. The drivers are optional peer dependencies; the package never installs one itself.

1. Add the comment table​

Export the table from your Drizzle schema and migrate the way you migrate the rest of it:

// src/db/schema.ts
export { respectifyComments } from '@respectify/astro/postgres'; // or '@respectify/astro/sqlite'
npx drizzle-kit generate
npx drizzle-kit migrate

The default tables are respectify_comment (Postgres) and Comment (SQLite). For another name use createPostgresCommentTable('my_comments') or createSqliteCommentTable('my_comments') and pass the table to the store. The integration never creates, alters or migrates a table itself.

2. Write the runtime module​

The store, and any functions, live in a module that runs inside your server bundle:

// src/respectify.runtime.ts
import { defineRespectifyRuntime } from '@respectify/astro/runtime';
import { createPostgresCommentStore } from '@respectify/astro/postgres';
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import { DATABASE_URL } from 'astro:env/server';

const db = drizzle({ client: new Pool({ connectionString: DATABASE_URL }) });

export default defineRespectifyRuntime({
store: createPostgresCommentStore(db),
// The canonical URL Respectify reads a post from, for topic context
getPostUrl: (slug, site) => `${site}/blog/${slug}/`,
});

Import defineRespectifyRuntime from @respectify/astro/runtime, not @respectify/astro: the main entry imports Astro's config, which bundling adapters such as Vercel cannot put in a server function. For SQLite use createSqliteCommentStore(db) from @respectify/astro/sqlite.

3. Add the integration​

// astro.config.ts
import { defineConfig, envField } from 'astro/config';
import node from '@astrojs/node';
import respectify from '@respectify/astro';

export default defineConfig({
site: 'https://yoursite.com',
output: 'server',
adapter: node({ mode: 'standalone' }),
env: {
schema: {
DATABASE_URL: envField.string({ context: 'server', access: 'secret' }),
},
},
integrations: [respectify()],
});

From 1.2.0 respectify() loads the runtime module from ./src/respectify.runtime.ts. Earlier versions, or a module kept somewhere else, need the path: respectify({ runtime: './src/respectify.runtime.ts' }).

4. Set your credentials​

RESPECTIFY_EMAIL=you@example.com
RESPECTIFY_API_KEY=your-api-key
DATABASE_URL=postgres://...

Credentials are read from the environment (or from client.email and client.apiKey in respectify.config.json). They are refused in astro.config, because those options are written into the server bundle.

5. Wire up the actions and the component​

// src/actions/index.ts
import { respectifyCommentActions } from '@respectify/astro/actions';

export const server = {
comments: respectifyCommentActions,
};
---
import CommentSection from '@respectify/astro/components/CommentSection.astro';
---

<CommentSection postSlug={post.id} />

A visitor's comment goes to the comments.submit action, which sends it to Respectify in one megacall with the checks you configured. An approved comment is saved through your store; a comment that falls short is sent back to the commenter with Respectify's feedback, and they can revise it.

Configuration​

Moderation policy lives in respectify.config.json in your project root. Start from one of the files the package ships:

# Minimal defaults
cp node_modules/@respectify/astro/default-respectify.config.json ./respectify.config.json

# Or the fully commented sample (strip the comments: JSON does not allow them)
cp node_modules/@respectify/astro/respectify.config.sample.jsonc ./respectify.config.json

The sections are:

SectionWhat it sets
enabledMaster switch. false skips Respectify and approves every comment
clientOptions forwarded to RespectifyClient: baseUrl, version, timeout, website
megacallWhich checks run: includeSpam, includeCommentScore, includeRelevance, includeDogwhistle, plus bannedTopics, sensitiveTopics and dogwhistleExamples
tolerancesComment health levels per item; items not named are standard. threat, identity_attack, sexual_content and harassment cannot be set below standard; the config fails to load if you try
moderationHow results become decisions: blockDisrespectful, allowOverride, showFeedbackToUser, blockOffTopic, blockDogwhistles
thresholdsThe respectfulness bands (1 - toxicity_score) that choose between a warning and a block when exceeds_tolerance is true
feedbackThe messages shown to commenters: approved, warning, blocked, offTopic, dogwhistle

Integration options​

respectify() in astro.config takes only values that can be serialized, because Astro runs the config apart from your server bundle. Values here override the same keys in respectify.config.json.

respectify({
runtime: './src/respectify.runtime.ts', // the default from 1.2.0; required before
configPath: './respectify.config.json',
commentsApiPath: '/api/respectify/comments',
showBranding: true,
// Per-IP submission limit in the comments.submit action, per server process
rateLimit: { windowMs: 300_000, maxRequests: 10 },
client: { timeout: 30_000, website: 'yoursite.com' },
megacall: { includeSpam: true, includeCommentScore: true, includeRelevance: true, includeDogwhistle: true },
tolerances: { insult: 'relaxed', threat: 'zero_tolerance', quality: 'strict' },
});

Runtime options​

Functions go in the runtime module, since they cannot be serialized into astro.config:

export default defineRespectifyRuntime({
store,
// The canonical URL for a post, used to initialize the Respectify topic
// (default: `${site}/posts/${slug}/`)
getPostUrl: (slug, site) => `${site}/posts/${slug}/`,
// Or hand Respectify the post body directly, for staged or auth-gated content.
// Takes priority over getPostUrl.
getPostContent: async (slug) => loadPostBody(slug),
// From 1.1.0: called for every comment published unmoderated because your free
// comments are used up. See "When the free plan runs out" below.
onModerationStopped: async ({ reason, upgradeUrl, message, postSlug }) => {
await sendOwnerEmail(`Respectify has stopped moderating (${reason}) on ${postSlug}: ${message}. Add credit: ${upgradeUrl}`);
},
// From 1.1.0: called when a comment is held for your review at the revision limit.
onHeldForReview: async ({ reason, comment }) => {
await sendOwnerEmail(`A comment on ${comment.postSlug} is waiting for review (${reason}).`);
},
});

Component props​

PropDefaultDescription
postSlugrequiredIdentifies the page the comments belong to
apiPath/api/respectify/commentsThe comments API path; must match commentsApiPath
showBrandingtrueShow the "Powered by Respectify" callout
enableDeletefalseShow delete controls when context.locals.isAuthenticated is true
classnoneExtra CSS class on the root element

Styling is self-contained CSS with variables you can override on .rf-comments, such as --rf-accent and --rf-radius.

Checking credentials​

import { verifyRespectifyCredentials } from '@respectify/astro/credentials';

const ok = await verifyRespectifyCredentials();

Returns true when the credentials are valid and the account can make calls: on the free plan with comments left, or with a balance above $0. It calls the free usercheck endpoint; see Verifying Credentials for the statuses it reads.

How Comments Are Decided​

Spam, off-topic and dogwhistle rejections come first. Suspected spam is not spam: the comment is sent back with the server's suggestion as feedback (such as "This looks like spam. How about removing the link?"), never approved. Then, on the comment score:

exceeds_toleranceRespectfulness (1 - toxicity_score)Result
falseanyApproved
truebelow thresholds.block, and blockDisrespectfulBlocked (feedback.blocked)
trueotherwiseWarning (feedback.warning); approved only when allowOverride
no comment scoreApproved

exceeds_tolerance reflects your tolerances, so it decides whether a comment has a problem at all; toxicity_score only chooses between a warning and a block. Replies pass the parent comment as replyToComment for context.

The Free Plan​

A new account has 200 free comments. The integration counts a comment once however many times the commenter revises it: it keeps the X-Respectify-Revision-Token Respectify returns with the first assessment and sends it back with each revision, so a visitor who needs three tries uses one free comment. Topic initialization is free and does not use one. See How free comments are counted.

When the Free Plan Runs Out​

Respectify emails the account owner at 160 comments used and again at 200, when moderation stops. From @respectify/astro 1.1.0, when the allowance is used up and the account has no credit:

  • Comments are approved unmoderated. The comments.submit action saves the comment through your store without a Respectify check, so your site keeps working. Commenters see nothing different. The action's result carries unmoderated: true, and the respectify:comment-published browser event has the same flag in its detail, in case you want to style or badge those comments; nothing is stored to mark them.
  • You are told. For every comment published this way the integration logs an error on the server with the upgrade URL, and calls onModerationStopped({ reason, upgradeUrl, message, postSlug }) from your runtime module if you set one. Use it to email yourself, post to a channel, or whatever reaches you; the integration does not send email itself, and a callback that throws is logged and never blocks the comment.

To resume moderation, add credit on your billing page. Any top-up ($5 minimum) does it, and the same API key keeps working: RESPECTIFY_API_KEY does not change, and the next comment is checked as normal.

The Revision Limit​

On the free plan each comment may be assessed 5 times: the original and 4 revisions. When a commenter submits a sixth version, Respectify returns HTTP 409 and the integration (from 1.1.0) holds the comment for you: it is saved in your comment store with approved = false, so it does not appear on the page (the integration never stored unapproved comments before, so such a row always means "held"), and the commenter is told it has been sent to the moderators. The action's result has heldForReview: true, the browser gets a respectify:comment-held event, and onHeldForReview({ reason, comment }) is called from your runtime module if you set it. Set approved to true or delete the row to deal with it; there is no admin screen. Accounts with credit have no such limit.

Rate limiting​

Free keys may make 30 requests a minute. The integration's own rateLimit option (10 submissions per IP per 5 minutes by default) keeps most sites well under that; a very busy free-plan site that goes over gets HTTP 429 from Respectify, which the action reports as a failed submission so the visitor can try again. Adding credit lifts the limit.

Upgrading from 0.x​

Version 1.0 replaced Astro DB with your own Drizzle database and moved functions out of astro.config into the runtime module. The package README's migration section walks through keeping an existing Turso database or moving comments to Postgres.

What's Next​