Adapters

Drizzle adapter

A production store on PostgreSQL or Turso / libSQL through Drizzle ORM — tables you own in your schema, migrations through drizzle-kit.

@siteping/adapter-drizzle is a SitepingStore backed by Drizzle ORM. It has one entry per database family:

EntryDatabaseDrivers
@siteping/adapter-drizzle/pgPostgreSQLAny Drizzle PostgreSQL driver — node-postgres, postgres.js, Neon (serverless and HTTP), Vercel Postgres, Supabase, PGlite…
@siteping/adapter-drizzle/libsqlTurso / libSQLdrizzle-orm/libsql only — Turso remote, embedded replicas, local files

It requires Node 22+ and drizzle-orm 0.45 or later (below 1.0), a peer dependency. @siteping/server serves the store over HTTP (step 3):

npm i @siteping/adapter-drizzle @siteping/server drizzle-orm

Add your database driver (pg, postgres, @neondatabase/serverless, @electric-sql/pglite, @libsql/client…) and drizzle-kit for migrations.

1. Add the tables to your schema

The adapter never creates tables at runtime: it gives you Drizzle table definitions to export from your own schema, so drizzle-kit manages them like any other table.

// db/schema.ts — PostgreSQL
import { createSitepingPgTables } from "@siteping/adapter-drizzle/pg";

export const { sitepingFeedbacks, sitepingAnnotations, sitepingComments } = createSitepingPgTables();
// db/schema.ts — Turso / libSQL
import { createSitepingSqliteTables } from "@siteping/adapter-drizzle/libsql";

export const { sitepingFeedbacks, sitepingAnnotations, sitepingComments } = createSitepingSqliteTables();

Then generate and apply the migration as usual, with a drizzle.config.ts pointing at that schema (dialect: "postgresql" or dialect: "turso"):

npx drizzle-kit generate   # writes the SQL migration
npx drizzle-kit migrate    # applies it — or `npx drizzle-kit push` while prototyping

What gets created

Three tables, siteping_feedbacks, siteping_annotations and siteping_comments by default — export and migrate all three: the store reads every feedback's thread, so the comments table is required even if nobody ever comments. Annotations and comments reference their feedback with ON DELETE CASCADE (on PostgreSQL, through the foreign keys <annotations>_feedback_id_fk and <comments>_feedback_id_fk).

IndexColumns
<feedbacks>_client_id_key (unique)client_id — arbitrates duplicate submissions
<feedbacks>_project_status_created_idxproject_name, status, created_at
<feedbacks>_project_url_idxproject_name, url
<annotations>_feedback_id_idxfeedback_id
<comments>_client_id_key (unique)client_id — arbitrates duplicate comments
<comments>_feedback_created_idxfeedback_id, created_at

Column types follow the dialect: on PostgreSQL, JSON fields are jsonb and timestamps are timestamptz(3); on libSQL, JSON fields are stored as text and timestamps as epoch milliseconds.

A JavaScript string can hold a NUL character, or half of a surrogate pair — text cut inside an emoji ends with one. PostgreSQL stores neither, so the store replaces each with U+FFFD, the Unicode replacement character, in everything it writes, on both dialects, and a record reads back exactly as it was returned. Search terms, filters and ids get the same replacement, so they find what was stored for them.

Custom table names

Pass { feedbacks, annotations, comments } to rename the tables (index names follow), and hand the same tables to the store through the tables option — otherwise it queries the default names:

// db/schema.ts
export const { sitepingFeedbacks, sitepingAnnotations, sitepingComments } = createSitepingPgTables({
  feedbacks: "client_feedbacks",
  annotations: "client_feedback_annotations",
  comments: "client_feedback_comments",
});

// server
const store = createPgSitepingStore(db, { tables: { sitepingFeedbacks, sitepingAnnotations, sitepingComments } });

The defaults are exported as DEFAULT_SITEPING_TABLE_NAMES.

On PostgreSQL, keep the feedback table's name within 36 bytes, the annotations' within 47 and the comments' within 42. PostgreSQL silently truncates identifiers past 63 bytes, and index and foreign-key names add a suffix to their table's name: a truncated name would make every later drizzle-kit push drop and recreate that index or constraint. createSitepingPgTables throws a RangeError for a name that is too long.

2. Create the store

// PostgreSQL — node-postgres
import { drizzle } from "drizzle-orm/node-postgres";
import { createPgSitepingStore } from "@siteping/adapter-drizzle/pg";

export const store = createPgSitepingStore(drizzle(process.env.DATABASE_URL!), { logger: console });

Every PostgreSQL driver works the same way — swap the drizzle import (drizzle-orm/neon-http, drizzle-orm/postgres-js, drizzle-orm/pglite…). The store never opens an interactive db.transaction: every write is a single statement, so drivers without interactive transactions, like Neon HTTP, are fully supported.

A database built with Drizzle's withReplicas(primary, replicas) works on both dialects: the store runs everything on the primary, reads included, since it reads back its own writes and a replica may lag.

// Turso / libSQL
import { drizzle } from "drizzle-orm/libsql";
import { createLibSQLSitepingStore } from "@siteping/adapter-drizzle/libsql";

export const store = createLibSQLSitepingStore(
  drizzle({ connection: { url: process.env.TURSO_DATABASE_URL!, authToken: process.env.TURSO_AUTH_TOKEN! } }),
  { logger: console },
);

Both factories also take a screenshotStorage, to keep screenshots out of the database — see screenshots.

3. Serve it

The store is storage only. Mount it behind createSitepingHandler({ store }) from @siteping/server to get validation, auth, CORS, redaction and webhooks:

// app/api/siteping/route.ts
import { createSitepingHandler } from "@siteping/server";
import { store } from "@/lib/siteping-store";

export const { GET, POST, PATCH, DELETE, OPTIONS } = createSitepingHandler({
  store,
  apiKey: process.env.SITEPING_API_KEY,
});

With a key, the widget can submit but not list its pins until GET is public — see the security model.

Options

Both factories take the same options:

OptionTypeDefaultWhat it does
tablesSitepingPgTables / SitepingSqliteTablesdefault-named tablesThe tables from your schema — required when you renamed them
screenshotStorageScreenshotStorage—Upload screenshots elsewhere and store only the URL — see screenshots
logger{ warn(message, context) }none — events are droppedDegraded-but-non-fatal events: a failed upload (the feedback is saved without its screenshot), a failed cleanup, inline screenshots. The store never picks a logging backend itself — pass your application's logger, or console, the same one the server's logger takes. One that throws or rejects never fails the store
now() => Datethe system clockClock for createdAt of new feedbacks and comments, and updatedAt on status updates — inject one for tests or a controlled time source

Screenshots

Without screenshotStorage, the screenshot's base64 data URL is stored inline in screenshot_url (with a one-time warning to the logger) — fine for development, heavy for production.

With screenshotStorage, upload(dataUrl, { feedbackId, mimeType }) runs before the insert and only the returned URL is stored:

  • feedbackId is the id the record will be stored under — generated server-side, fresh for every create attempt, never the client's clientId.
  • mimeType is the media type the data URL declares — image/jpeg, image/png or image/webp, lowercased. Anything else (an SVG, which is script-capable when served inline, or no type at all) is reported as image/jpeg, the widget's capture format. Use it as the object's Content-Type.
  • If upload throws, the feedback is still saved with screenshotUrl: null, and the failure goes to the logger.

The returned URL must be unique to the upload. Key objects by a fresh random value — never by a content hash, a fixed name or feedbackId alone. feedbackId is the stored feedback's id with every bundled store, but a ScreenshotStorage does not know which store calls it, and a store of your own may pass anything. The store treats each URL as owned by the one feedback that stores it and may pass it to delete without coordinating with concurrent creates; a URL shared by several feedbacks can lose an object another feedback still points at.

Ready-made storage. @siteping/screenshot-storage provides a screenshotStorage for S3-compatible buckets, Cloudflare Images or your disk, with random keys and deletes scoped to its own objects. Its /drizzle-pg and /drizzle-libsql entries can also keep screenshots in a table of this same database, for small or self-contained deployments; in production, object storage is the better choice.

Cleanup. Add an optional delete(url) and the store removes screenshots it no longer needs: on deleteFeedback, on deleteAllFeedbacks, when a submission loses a race against a duplicate of itself (it uploaded its own object, now an orphan — discarded even when reading the winning submission back then fails), and when an insert fails. Before any delete it checks that no stored feedback still references the URL — an insert reported as failed may have committed after all — and if that check itself fails, every object is kept. Deletes run at most 32 at a time, so a project delete freeing thousands of objects does not flood your storage. Cleanup is best-effort: a failing delete is logged and never fails the operation. Inline data: URLs are never passed to delete.

Large projects. With a delete hook, deleteAllFeedbacks needs the removed URLs back, so it deletes the project in chunks of 500 rows — each chunk atomically, its screenshots cleaned up before the next — and no driver response or in-memory list grows with the project. If a chunk fails, the call throws StorePersistenceError: the earlier chunks stay deleted and cleaned up, and retrying the call removes the rest. The call returns once the project is empty, even when another delete of the same project runs alongside (a double click, a retried request). If the database keeps rows it is told to delete — a row-level security policy or a trigger that skips deletes — it throws StorePersistenceError instead of retrying forever. Without a delete hook the whole project goes in one atomic statement.

Concurrency guarantees

  • Duplicate submissions are atomic. The store implements createFeedbackIfAbsent: the unique client_id index plus ON CONFLICT DO NOTHING arbitrate concurrent submissions of the same feedback, across store instances and processes. Exactly one caller gets created: true, so the handler notifies your webhooks once, whichever server instance each request reached. Replies get the same through addCommentIfAbsent, for the comment.created webhook and onCommentCreated.
  • Annotations land with their feedback, or not at all. On PostgreSQL the feedback and its annotations are inserted by one statement (a data-modifying CTE). On libSQL, multi-statement writes go through db.batch, which runs as one transaction and never holds the write lock across an await — your application can keep writing to the same database concurrently.
  • Comments land whole, or not at all. A comment is inserted by one INSERT … SELECT that writes only when its feedback exists and, for a client comment, its thread holds fewer than 100 of them, with ON CONFLICT DO NOTHING on client_id: a replayed post returns the stored comment, across store instances and processes. Posts racing for the last free slot may overshoot the cap.
  • Ordering is stable. Lists come back newest first. createdAt is the clock value at insert time, and rows created in the same millisecond — by one store instance, several processes, or your own code inserting through the exported tables — are ordered by an insertion ordinal the database itself assigns on every insert: the internal creation_sequence identity on PostgreSQL, SQLite's implicit rowid on libSQL. A later insert always lists first, and offset pages never overlap or skip rows. A thread reads oldest first, and comments posted within one millisecond keep their posting order through their position.
  • updatedAt never precedes createdAt. Status updates clamp it in SQL against the row's own timestamps, which holds across processes whose clocks disagree.
  • Project ownership. The store implements verifyProjectOwnership, so the handler answers 404 to a PATCH/DELETE addressing an id from another project.

Internal columns

The tables carry a few columns of the store's own, never part of the returned records:

ColumnTablePurpose
positionannotations, commentsInteger (default 0) keeping each feedback's annotations in submission order — annotations[0] is the primary anchor — and each thread in posting order: a comment insert takes one past the thread's highest
creation_sequencefeedbacks (PostgreSQL only)Breaks created_at ties: a bigint identity the database assigns on every insert, the store's or yours. libSQL has no such column — it orders by the implicit rowid
message_searchfeedbacksNullable text: the message lowercased in JavaScript, read by the text search — see below

Text search and non-ASCII case

getFeedbacks({ search }) — the search query parameter — matches the message case-insensitively with JavaScript's Unicode-aware toLowerCase(), the same folding as the memory and localStorage stores: échec finds Échec and äöü finds ÄÖÜ, whatever the database's own rules. That is what message_search is for: SQLite's LIKE folds only ASCII case, and PostgreSQL's ILIKE folds with the column collation / LC_CTYPE (ASCII-only under C). The store fills message_search on insert and matches the lowercased term against it with a plain LIKE. Wildcards typed in the search (%, _, \) are matched literally.

Rows without it — inserted by your own code outside the store — fall back to searching message with the database's folding (LIKE on libSQL, ILIKE on PostgreSQL). Backfill them once so every row folds Unicode case:

import { eq, isNull } from "drizzle-orm";

const rows = await db
  .select({ id: sitepingFeedbacks.id, message: sitepingFeedbacks.message })
  .from(sitepingFeedbacks)
  .where(isNull(sitepingFeedbacks.messageSearch));

for (const row of rows) {
  await db
    .update(sitepingFeedbacks)
    .set({ messageSearch: row.message.toLowerCase() })
    .where(eq(sitepingFeedbacks.id, row.id));
}

Run the backfill in JavaScript, not with SQL lower(): the database's lower() follows the same locale rules the column exists to avoid.

Errors

  • A database failure during a mutation (read-only or full database, lost connection, rejected statement…) surfaces as StorePersistenceError, with the driver error as cause — the failure of a read the mutation makes too, such as the clientId lookup before an insert. Detect it with isStorePersistence.
  • No error the store throws carries the statement or its values. Drizzle wraps a failed query in a DrizzleQueryError whose message lists every bound value — author emails, messages, inline screenshots — PGlite and postgres.js attach them to their own errors, and loggers print an error's cause. So the store reports a copy of the driver's error, from failed reads too: a plain Error with the driver error's name, message, stack, codes (a PostgreSQL SQLSTATE and the constraint, table or column it names, a SQLITE_* code) and cause chain. Match on code, not on the driver's error class. PostgreSQL's detail is left out: for a NOT NULL or CHECK violation, it holds the whole failing row.
  • updateFeedback reads the (immutable) annotations and the thread before updating the row, so no database call runs after the update commits: a failed read leaves the row untouched, and an applied update is never reported as failed because of a read that followed it.
  • updateFeedback and deleteFeedback on an unknown id throw StoreNotFoundError, and so do addComment on an unknown feedback — including one deleted while the comment is being inserted — and deleteComment of a comment that is not on that feedback's thread. addComment on a full thread throws StoreLimitError.

Both entries re-export the store errors and their guards — StorePersistenceError, StoreNotFoundError, StoreDuplicateError, StoreLimitError, StoreValueTooLongError, and isStorePersistence, isStoreNotFound, isStoreDuplicate, isStoreLimit, isStoreValueTooLong — so you can catch them without another import.

Limitations

  • PostgreSQL and libSQL only. There is no MySQL entry yet.
  • libSQL only through drizzle-orm/libsql or its variants (/web, /http, /ws…). Other SQLite drivers (better-sqlite3, Cloudflare D1) are not supported: createLibSQLSitepingStore throws a TypeError when given their database, which the types of a Workers project may accept.
  • One local libSQL file shared by several processes. SQLite runs one writer at a time: with @libsql/client 0.17.4 or later, set the client's busy timeout — drizzle({ connection: { url: "file:siteping.db", timeout: 5000 } }) — so concurrent writes queue instead of failing with SQLITE_BUSY. Older clients ignore it silently, even where TypeScript accepts it (client 0.17.3 installs a newer @libsql/core, which declares it): upgrade first.
  • Foreign keys on libSQL. Cascades need PRAGMA foreign_keys = ON, which libSQL does not guarantee, so the store deletes annotations and comments explicitly alongside their feedback. Feedbacks you delete yourself outside the store need the same care.
  • Search on rows without message_search folds case the database's way (ASCII-only on libSQL, and on PostgreSQL under a C collation / LC_CTYPE) until you backfill them.
Edit on GitHub

On this page